1 # Copyright (C) 2007-2016 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
32 ## These are methods of class \ref smeshBuilder.smeshBuilder "smeshBuilder"
34 ## @defgroup l2_construct Constructing meshes
35 ## @defgroup l2_algorithms Defining Algorithms
37 ## @defgroup l3_algos_basic Basic meshing algorithms
38 ## @defgroup l3_algos_proj Projection Algorithms
39 ## @defgroup l3_algos_segmarv Segments around Vertex
40 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
43 ## @defgroup l2_hypotheses Defining hypotheses
45 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
46 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
47 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
48 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
49 ## @defgroup l3_hypos_additi Additional Hypotheses
52 ## @defgroup l2_submeshes Constructing sub-meshes
53 ## @defgroup l2_editing Editing Meshes
56 ## @defgroup l1_meshinfo Mesh Information
57 ## @defgroup l1_controls Quality controls and Filtering
58 ## @defgroup l1_grouping Grouping elements
60 ## @defgroup l2_grps_create Creating groups
61 ## @defgroup l2_grps_operon Using operations on groups
62 ## @defgroup l2_grps_delete Deleting Groups
65 ## @defgroup l1_modifying Modifying meshes
67 ## @defgroup l2_modif_add Adding nodes and elements
68 ## @defgroup l2_modif_del Removing nodes and elements
69 ## @defgroup l2_modif_edit Modifying nodes and elements
70 ## @defgroup l2_modif_renumber Renumbering nodes and elements
71 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
78 ## @defgroup l2_modif_duplicat Duplication of nodes and elements (to emulate cracks)
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
88 from salome.smesh.smesh_algorithm import Mesh_Algorithm
94 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
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 ## Convert 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 while 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):
166 "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
167 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
169 SMESH.AxisStruct.__init__ = __initAxisStruct
171 smeshPrecisionConfusion = 1.e-07
172 ## Compare real values using smeshPrecisionConfusion as tolerance
173 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
174 if abs(val1 - val2) < tol:
180 ## Return object name
184 if isinstance(obj, SALOMEDS._objref_SObject):
188 ior = salome.orb.object_to_string(obj)
192 sobj = salome.myStudy.FindObjectIOR(ior)
194 return sobj.GetName()
195 if hasattr(obj, "GetName"):
196 # unknown CORBA object, having GetName() method
199 # unknown CORBA object, no GetName() method
202 if hasattr(obj, "GetName"):
203 # unknown non-CORBA object, having GetName() method
206 raise RuntimeError, "Null or invalid object"
208 ## Print error message if a hypothesis was not assigned.
209 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
211 hypType = "algorithm"
213 hypType = "hypothesis"
216 if hasattr( status, "__getitem__" ):
217 status,reason = status[0],status[1]
218 if status == HYP_UNKNOWN_FATAL :
219 reason = "for unknown reason"
220 elif status == HYP_INCOMPATIBLE :
221 reason = "this hypothesis mismatches the algorithm"
222 elif status == HYP_NOTCONFORM :
223 reason = "a non-conform mesh would be built"
224 elif status == HYP_ALREADY_EXIST :
225 if isAlgo: return # it does not influence anything
226 reason = hypType + " of the same dimension is already assigned to this shape"
227 elif status == HYP_BAD_DIM :
228 reason = hypType + " mismatches the shape"
229 elif status == HYP_CONCURENT :
230 reason = "there are concurrent hypotheses on sub-shapes"
231 elif status == HYP_BAD_SUBSHAPE :
232 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
233 elif status == HYP_BAD_GEOMETRY:
234 reason = "the algorithm is not applicable to this geometry"
235 elif status == HYP_HIDDEN_ALGO:
236 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
237 elif status == HYP_HIDING_ALGO:
238 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
239 elif status == HYP_NEED_SHAPE:
240 reason = "algorithm can't work without shape"
241 elif status == HYP_INCOMPAT_HYPS:
247 where = '"%s"' % geomName
249 meshName = GetName( mesh )
250 if meshName and meshName != NO_NAME:
251 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
252 if status < HYP_UNKNOWN_FATAL and where:
253 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
255 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
257 print '"%s" was not assigned : %s' %( hypName, reason )
260 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
261 def AssureGeomPublished(mesh, geom, name=''):
262 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
264 if not geom.GetStudyEntry():
266 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
267 # for all groups SubShapeName() return "Compound_-1"
268 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
270 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
272 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
275 ## Return the first vertex of a geometrical edge by ignoring orientation
276 def FirstVertexOnCurve(mesh, edge):
277 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
279 raise TypeError, "Given object has no vertices"
280 if len( vv ) == 1: return vv[0]
281 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
282 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
283 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
284 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
287 dist1 += abs( xyz[i] - xyz1[i] )
288 dist2 += abs( xyz[i] - xyz2[i] )
294 # end of l1_auxiliary
298 # Warning: smeshInst is a singleton
304 ## This class allows to create, load or manipulate meshes.
305 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
306 # It also has methods to get infos and measure meshes.
307 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
309 # MirrorType enumeration
310 POINT = SMESH_MeshEditor.POINT
311 AXIS = SMESH_MeshEditor.AXIS
312 PLANE = SMESH_MeshEditor.PLANE
314 # Smooth_Method enumeration
315 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
316 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
318 PrecisionConfusion = smeshPrecisionConfusion
320 # TopAbs_State enumeration
321 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
323 # Methods of splitting a hexahedron into tetrahedra
324 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
330 #print "==== __new__", engine, smeshInst, doLcc
332 if smeshInst is None:
333 # smesh engine is either retrieved from engine, or created
335 # Following test avoids a recursive loop
337 if smeshInst is not None:
338 # smesh engine not created: existing engine found
342 # FindOrLoadComponent called:
343 # 1. CORBA resolution of server
344 # 2. the __new__ method is called again
345 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
346 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
348 # FindOrLoadComponent not called
349 if smeshInst is None:
350 # smeshBuilder instance is created from lcc.FindOrLoadComponent
351 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
352 smeshInst = super(smeshBuilder,cls).__new__(cls)
354 # smesh engine not created: existing engine found
355 #print "==== existing ", engine, smeshInst, doLcc
357 #print "====1 ", smeshInst
360 #print "====2 ", smeshInst
365 #print "--------------- smeshbuilder __init__ ---", created
368 SMESH._objref_SMESH_Gen.__init__(self)
370 ## Dump component to the Python script
371 # This method overrides IDL function to allow default values for the parameters.
372 # @ingroup l1_auxiliary
373 def DumpPython(self, theIsPublished=True, theIsMultiFile=True):
374 return SMESH._objref_SMESH_Gen.DumpPython(self, theIsPublished, theIsMultiFile)
376 ## Set mode of DumpPython(), \a historical or \a snapshot.
377 # In the \a historical mode, the Python Dump script includes all commands
378 # performed by SMESH engine. In the \a snapshot mode, commands
379 # relating to objects removed from the Study are excluded from the script
380 # as well as commands not influencing the current state of meshes
381 # @ingroup l1_auxiliary
382 def SetDumpPythonHistorical(self, isHistorical):
383 if isHistorical: val = "true"
385 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
387 ## Set Geometry component
388 # @ingroup l1_auxiliary
389 def init_smesh(self,isPublished = True,geompyD = None):
391 self.UpdateStudy(geompyD)
394 notebook.myStudy = salome.myStudy
396 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
397 # or a mesh wrapping a CORBA mesh given as a parameter.
398 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
399 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
400 # (2) a Geometrical object for meshing or
402 # @param name the name for the new mesh.
403 # @return an instance of Mesh class.
404 # @ingroup l2_construct
405 def Mesh(self, obj=0, name=0):
406 if isinstance(obj,str):
408 return Mesh(self,self.geompyD,obj,name)
410 ## Return a long value from enumeration
411 # @ingroup l1_auxiliary
412 def EnumToLong(self,theItem):
415 ## Return a string representation of the color.
416 # To be used with filters.
417 # @param c color value (SALOMEDS.Color)
418 # @ingroup l1_auxiliary
419 def ColorToString(self,c):
421 if isinstance(c, SALOMEDS.Color):
422 val = "%s;%s;%s" % (c.R, c.G, c.B)
423 elif isinstance(c, str):
426 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
429 ## Get PointStruct from vertex
430 # @param theVertex a GEOM object(vertex)
431 # @return SMESH.PointStruct
432 # @ingroup l1_auxiliary
433 def GetPointStruct(self,theVertex):
434 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
435 return PointStruct(x,y,z)
437 ## Get DirStruct from vector
438 # @param theVector a GEOM object(vector)
439 # @return SMESH.DirStruct
440 # @ingroup l1_auxiliary
441 def GetDirStruct(self,theVector):
442 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
443 if(len(vertices) != 2):
444 print "Error: vector object is incorrect."
446 p1 = self.geompyD.PointCoordinates(vertices[0])
447 p2 = self.geompyD.PointCoordinates(vertices[1])
448 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
449 dirst = DirStruct(pnt)
452 ## Make DirStruct from a triplet
453 # @param x,y,z vector components
454 # @return SMESH.DirStruct
455 # @ingroup l1_auxiliary
456 def MakeDirStruct(self,x,y,z):
457 pnt = PointStruct(x,y,z)
458 return DirStruct(pnt)
460 ## Get AxisStruct from object
461 # @param theObj a GEOM object (line or plane)
462 # @return SMESH.AxisStruct
463 # @ingroup l1_auxiliary
464 def GetAxisStruct(self,theObj):
466 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
469 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
470 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
471 vertex1 = self.geompyD.PointCoordinates(vertex1)
472 vertex2 = self.geompyD.PointCoordinates(vertex2)
473 vertex3 = self.geompyD.PointCoordinates(vertex3)
474 vertex4 = self.geompyD.PointCoordinates(vertex4)
475 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
476 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
477 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] ]
478 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
479 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
480 elif len(edges) == 1:
481 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
482 p1 = self.geompyD.PointCoordinates( vertex1 )
483 p2 = self.geompyD.PointCoordinates( vertex2 )
484 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
485 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
486 elif theObj.GetShapeType() == GEOM.VERTEX:
487 x,y,z = self.geompyD.PointCoordinates( theObj )
488 axis = AxisStruct( x,y,z, 1,0,0,)
489 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
492 # From SMESH_Gen interface:
493 # ------------------------
495 ## Set the given name to the object
496 # @param obj the object to rename
497 # @param name a new object name
498 # @ingroup l1_auxiliary
499 def SetName(self, obj, name):
500 if isinstance( obj, Mesh ):
502 elif isinstance( obj, Mesh_Algorithm ):
503 obj = obj.GetAlgorithm()
504 ior = salome.orb.object_to_string(obj)
505 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
507 ## Set the current mode
508 # @ingroup l1_auxiliary
509 def SetEmbeddedMode( self,theMode ):
510 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
512 ## Get the current mode
513 # @ingroup l1_auxiliary
514 def IsEmbeddedMode(self):
515 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
517 ## Update the current study. Calling UpdateStudy() allows to
518 # update meshes at switching GEOM->SMESH
519 # @ingroup l1_auxiliary
520 def UpdateStudy( self, geompyD = None ):
523 from salome.geom import geomBuilder
524 geompyD = geomBuilder.geom
527 self.SetGeomEngine(geompyD)
528 SMESH._objref_SMESH_Gen.UpdateStudy(self)
529 sb = salome.myStudy.NewBuilder()
530 sc = salome.myStudy.FindComponent("SMESH")
531 if sc: sb.LoadWith(sc, self)
534 ## Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to
535 # switch OFF publishing in the Study of mesh objects.
536 # @ingroup l1_auxiliary
537 def SetEnablePublish( self, theIsEnablePublish ):
538 #self.SetEnablePublish(theIsEnablePublish)
539 SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
541 notebook = salome_notebook.NoteBook( theIsEnablePublish )
543 ## Create a Mesh object importing data from the given UNV file
544 # @return an instance of Mesh class
546 def CreateMeshesFromUNV( self,theFileName ):
547 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
548 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
551 ## Create a Mesh object(s) importing data from the given MED file
552 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
554 def CreateMeshesFromMED( self,theFileName ):
555 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
556 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
557 return aMeshes, aStatus
559 ## Create a Mesh object(s) importing data from the given SAUV file
560 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
562 def CreateMeshesFromSAUV( self,theFileName ):
563 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
564 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
565 return aMeshes, aStatus
567 ## Create a Mesh object importing data from the given STL file
568 # @return an instance of Mesh class
570 def CreateMeshesFromSTL( self, theFileName ):
571 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
572 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
575 ## Create Mesh objects importing data from the given CGNS file
576 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
578 def CreateMeshesFromCGNS( self, theFileName ):
579 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
580 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
581 return aMeshes, aStatus
583 ## Create a Mesh object importing data from the given GMF file.
584 # GMF files must have .mesh extension for the ASCII format and .meshb for
586 # @return [ an instance of Mesh class, SMESH.ComputeError ]
588 def CreateMeshesFromGMF( self, theFileName ):
589 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
592 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
593 return Mesh(self, self.geompyD, aSmeshMesh), error
595 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
596 # present in the new mesh.
597 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
598 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
599 # @param mergeNodesAndElements if true, equal nodes and elements are merged
600 # @param mergeTolerance tolerance for merging nodes
601 # @param allGroups forces creation of groups corresponding to every input mesh
602 # @param name name of a new mesh
603 # @return an instance of Mesh class
604 # @ingroup l1_creating
605 def Concatenate( self, meshes, uniteIdenticalGroups,
606 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
608 if not meshes: return None
609 for i,m in enumerate(meshes):
610 if isinstance(m, Mesh):
611 meshes[i] = m.GetMesh()
612 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
613 meshes[0].SetParameters(Parameters)
615 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
616 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
618 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
619 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
620 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
623 ## Create a mesh by copying a part of another mesh.
624 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
625 # to copy nodes or elements not contained in any mesh object,
626 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
627 # @param meshName a name of the new mesh
628 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
629 # @param toKeepIDs to preserve order of the copied elements or not
630 # @return an instance of Mesh class
631 # @ingroup l1_creating
632 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
633 if (isinstance( meshPart, Mesh )):
634 meshPart = meshPart.GetMesh()
635 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
636 return Mesh(self, self.geompyD, mesh)
638 ## Return IDs of sub-shapes
639 # @return the list of integer values
640 # @ingroup l1_auxiliary
641 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
642 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
644 ## Create a pattern mapper.
645 # @return an instance of SMESH_Pattern
647 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
648 # @ingroup l1_modifying
649 def GetPattern(self):
650 return SMESH._objref_SMESH_Gen.GetPattern(self)
652 ## Set number of segments per diagonal of boundary box of geometry, by which
653 # default segment length of appropriate 1D hypotheses is defined in GUI.
654 # Default value is 10.
655 # @ingroup l1_auxiliary
656 def SetBoundaryBoxSegmentation(self, nbSegments):
657 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
659 # Filtering. Auxiliary functions:
660 # ------------------------------
662 ## Create an empty criterion
663 # @return SMESH.Filter.Criterion
664 # @ingroup l1_controls
665 def GetEmptyCriterion(self):
666 Type = self.EnumToLong(FT_Undefined)
667 Compare = self.EnumToLong(FT_Undefined)
671 UnaryOp = self.EnumToLong(FT_Undefined)
672 BinaryOp = self.EnumToLong(FT_Undefined)
675 Precision = -1 ##@1e-07
676 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
677 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
679 ## Create a criterion by the given parameters
680 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
681 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
682 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
683 # Type SMESH.FunctorType._items in the Python Console to see all values.
684 # Note that the items starting from FT_LessThan are not suitable for CritType.
685 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
686 # @param Threshold the threshold value (range of ids as string, shape, numeric)
687 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
688 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
690 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
691 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
692 # @return SMESH.Filter.Criterion
694 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
695 # @ingroup l1_controls
696 def GetCriterion(self,elementType,
698 Compare = FT_EqualTo,
700 UnaryOp=FT_Undefined,
701 BinaryOp=FT_Undefined,
703 if not CritType in SMESH.FunctorType._items:
704 raise TypeError, "CritType should be of SMESH.FunctorType"
705 aCriterion = self.GetEmptyCriterion()
706 aCriterion.TypeOfElement = elementType
707 aCriterion.Type = self.EnumToLong(CritType)
708 aCriterion.Tolerance = Tolerance
710 aThreshold = Threshold
712 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
713 aCriterion.Compare = self.EnumToLong(Compare)
714 elif Compare == "=" or Compare == "==":
715 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
717 aCriterion.Compare = self.EnumToLong(FT_LessThan)
719 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
720 elif Compare != FT_Undefined:
721 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
724 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
725 FT_BelongToCylinder, FT_LyingOnGeom]:
726 # Check that Threshold is GEOM object
727 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
728 aCriterion.ThresholdStr = GetName(aThreshold)
729 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
730 if not aCriterion.ThresholdID:
731 name = aCriterion.ThresholdStr
733 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
734 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
735 # or a name of GEOM object
736 elif isinstance( aThreshold, str ):
737 aCriterion.ThresholdStr = aThreshold
739 raise TypeError, "The Threshold should be a shape."
740 if isinstance(UnaryOp,float):
741 aCriterion.Tolerance = UnaryOp
742 UnaryOp = FT_Undefined
744 elif CritType == FT_BelongToMeshGroup:
745 # Check that Threshold is a group
746 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
747 if aThreshold.GetType() != elementType:
748 raise ValueError, "Group type mismatches Element type"
749 aCriterion.ThresholdStr = aThreshold.GetName()
750 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
751 study = salome.myStudy
753 so = study.FindObjectIOR( aCriterion.ThresholdID )
757 aCriterion.ThresholdID = entry
759 raise TypeError, "The Threshold should be a Mesh Group"
760 elif CritType == FT_RangeOfIds:
761 # Check that Threshold is string
762 if isinstance(aThreshold, str):
763 aCriterion.ThresholdStr = aThreshold
765 raise TypeError, "The Threshold should be a string."
766 elif CritType == FT_CoplanarFaces:
767 # Check the Threshold
768 if isinstance(aThreshold, int):
769 aCriterion.ThresholdID = str(aThreshold)
770 elif isinstance(aThreshold, str):
773 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
774 aCriterion.ThresholdID = aThreshold
777 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
778 elif CritType == FT_ConnectedElements:
779 # Check the Threshold
780 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
781 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
782 if not aCriterion.ThresholdID:
783 name = aThreshold.GetName()
785 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
786 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
787 elif isinstance(aThreshold, int): # node id
788 aCriterion.Threshold = aThreshold
789 elif isinstance(aThreshold, list): # 3 point coordinates
790 if len( aThreshold ) < 3:
791 raise ValueError, "too few point coordinates, must be 3"
792 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
793 elif isinstance(aThreshold, str):
794 if aThreshold.isdigit():
795 aCriterion.Threshold = aThreshold # node id
797 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
800 "The Threshold should either a VERTEX, or a node ID, "\
801 "or a list of point coordinates and not '%s'"%aThreshold
802 elif CritType == FT_ElemGeomType:
803 # Check the Threshold
805 aCriterion.Threshold = self.EnumToLong(aThreshold)
806 assert( aThreshold in SMESH.GeometryType._items )
808 if isinstance(aThreshold, int):
809 aCriterion.Threshold = aThreshold
811 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
814 elif CritType == FT_EntityType:
815 # Check the Threshold
817 aCriterion.Threshold = self.EnumToLong(aThreshold)
818 assert( aThreshold in SMESH.EntityType._items )
820 if isinstance(aThreshold, int):
821 aCriterion.Threshold = aThreshold
823 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
827 elif CritType == FT_GroupColor:
828 # Check the Threshold
830 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
832 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
834 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
835 FT_LinearOrQuadratic, FT_BadOrientedVolume,
836 FT_BareBorderFace, FT_BareBorderVolume,
837 FT_OverConstrainedFace, FT_OverConstrainedVolume,
838 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
839 # At this point the Threshold is unnecessary
840 if aThreshold == FT_LogicalNOT:
841 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
842 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
843 aCriterion.BinaryOp = aThreshold
847 aThreshold = float(aThreshold)
848 aCriterion.Threshold = aThreshold
850 raise TypeError, "The Threshold should be a number."
853 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
854 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
856 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
857 aCriterion.BinaryOp = self.EnumToLong(Threshold)
859 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
860 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
862 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
863 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
867 ## Create a filter with the given parameters
868 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
869 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
870 # Type SMESH.FunctorType._items in the Python Console to see all values.
871 # Note that the items starting from FT_LessThan are not suitable for CritType.
872 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
873 # @param Threshold the threshold value (range of ids as string, shape, numeric)
874 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
875 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
876 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
877 # @param mesh the mesh to initialize the filter with
878 # @return SMESH_Filter
880 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
881 # @ingroup l1_controls
882 def GetFilter(self,elementType,
883 CritType=FT_Undefined,
886 UnaryOp=FT_Undefined,
889 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
890 aFilterMgr = self.CreateFilterManager()
891 aFilter = aFilterMgr.CreateFilter()
893 aCriteria.append(aCriterion)
894 aFilter.SetCriteria(aCriteria)
896 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
897 else : aFilter.SetMesh( mesh )
898 aFilterMgr.UnRegister()
901 ## Create a filter from criteria
902 # @param criteria a list of criteria
903 # @param binOp binary operator used when binary operator of criteria is undefined
904 # @return SMESH_Filter
906 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
907 # @ingroup l1_controls
908 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
909 for i in range( len( criteria ) - 1 ):
910 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
911 criteria[i].BinaryOp = self.EnumToLong( binOp )
912 aFilterMgr = self.CreateFilterManager()
913 aFilter = aFilterMgr.CreateFilter()
914 aFilter.SetCriteria(criteria)
915 aFilterMgr.UnRegister()
918 ## Create a numerical functor by its type
919 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
920 # Type SMESH.FunctorType._items in the Python Console to see all items.
921 # Note that not all items correspond to numerical functors.
922 # @return SMESH_NumericalFunctor
923 # @ingroup l1_controls
924 def GetFunctor(self,theCriterion):
925 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
927 aFilterMgr = self.CreateFilterManager()
929 if theCriterion == FT_AspectRatio:
930 functor = aFilterMgr.CreateAspectRatio()
931 elif theCriterion == FT_AspectRatio3D:
932 functor = aFilterMgr.CreateAspectRatio3D()
933 elif theCriterion == FT_Warping:
934 functor = aFilterMgr.CreateWarping()
935 elif theCriterion == FT_MinimumAngle:
936 functor = aFilterMgr.CreateMinimumAngle()
937 elif theCriterion == FT_Taper:
938 functor = aFilterMgr.CreateTaper()
939 elif theCriterion == FT_Skew:
940 functor = aFilterMgr.CreateSkew()
941 elif theCriterion == FT_Area:
942 functor = aFilterMgr.CreateArea()
943 elif theCriterion == FT_Volume3D:
944 functor = aFilterMgr.CreateVolume3D()
945 elif theCriterion == FT_MaxElementLength2D:
946 functor = aFilterMgr.CreateMaxElementLength2D()
947 elif theCriterion == FT_MaxElementLength3D:
948 functor = aFilterMgr.CreateMaxElementLength3D()
949 elif theCriterion == FT_MultiConnection:
950 functor = aFilterMgr.CreateMultiConnection()
951 elif theCriterion == FT_MultiConnection2D:
952 functor = aFilterMgr.CreateMultiConnection2D()
953 elif theCriterion == FT_Length:
954 functor = aFilterMgr.CreateLength()
955 elif theCriterion == FT_Length2D:
956 functor = aFilterMgr.CreateLength2D()
957 elif theCriterion == FT_NodeConnectivityNumber:
958 functor = aFilterMgr.CreateNodeConnectivityNumber()
959 elif theCriterion == FT_BallDiameter:
960 functor = aFilterMgr.CreateBallDiameter()
962 print "Error: given parameter is not numerical functor type."
963 aFilterMgr.UnRegister()
967 # @param theHType mesh hypothesis type (string)
968 # @param theLibName mesh plug-in library name
969 # @return created hypothesis instance
970 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
971 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
973 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
976 # wrap hypothesis methods
977 #print "HYPOTHESIS", theHType
978 for meth_name in dir( hyp.__class__ ):
979 if not meth_name.startswith("Get") and \
980 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
981 method = getattr ( hyp.__class__, meth_name )
983 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
987 ## Get the mesh statistic
988 # @return dictionary "element type" - "count of elements"
989 # @ingroup l1_meshinfo
990 def GetMeshInfo(self, obj):
991 if isinstance( obj, Mesh ):
994 if hasattr(obj, "GetMeshInfo"):
995 values = obj.GetMeshInfo()
996 for i in range(SMESH.Entity_Last._v):
997 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1001 ## Get minimum distance between two objects
1003 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1004 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1006 # @param src1 first source object
1007 # @param src2 second source object
1008 # @param id1 node/element id from the first source
1009 # @param id2 node/element id from the second (or first) source
1010 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1011 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1012 # @return minimum distance value
1013 # @sa GetMinDistance()
1014 # @ingroup l1_measurements
1015 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1016 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1020 result = result.value
1023 ## Get measure structure specifying minimum distance data between two objects
1025 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1026 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1028 # @param src1 first source object
1029 # @param src2 second source object
1030 # @param id1 node/element id from the first source
1031 # @param id2 node/element id from the second (or first) source
1032 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1033 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1034 # @return Measure structure or None if input data is invalid
1036 # @ingroup l1_measurements
1037 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1038 if isinstance(src1, Mesh): src1 = src1.mesh
1039 if isinstance(src2, Mesh): src2 = src2.mesh
1040 if src2 is None and id2 != 0: src2 = src1
1041 if not hasattr(src1, "_narrow"): return None
1042 src1 = src1._narrow(SMESH.SMESH_IDSource)
1043 if not src1: return None
1044 unRegister = genObjUnRegister()
1047 e = m.GetMeshEditor()
1049 src1 = e.MakeIDSource([id1], SMESH.FACE)
1051 src1 = e.MakeIDSource([id1], SMESH.NODE)
1052 unRegister.set( src1 )
1054 if hasattr(src2, "_narrow"):
1055 src2 = src2._narrow(SMESH.SMESH_IDSource)
1056 if src2 and id2 != 0:
1058 e = m.GetMeshEditor()
1060 src2 = e.MakeIDSource([id2], SMESH.FACE)
1062 src2 = e.MakeIDSource([id2], SMESH.NODE)
1063 unRegister.set( src2 )
1066 aMeasurements = self.CreateMeasurements()
1067 unRegister.set( aMeasurements )
1068 result = aMeasurements.MinDistance(src1, src2)
1071 ## Get bounding box of the specified object(s)
1072 # @param objects single source object or list of source objects
1073 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1074 # @sa GetBoundingBox()
1075 # @ingroup l1_measurements
1076 def BoundingBox(self, objects):
1077 result = self.GetBoundingBox(objects)
1081 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1084 ## Get measure structure specifying bounding box data of the specified object(s)
1085 # @param objects single source object or list of source objects
1086 # @return Measure structure
1088 # @ingroup l1_measurements
1089 def GetBoundingBox(self, objects):
1090 if isinstance(objects, tuple):
1091 objects = list(objects)
1092 if not isinstance(objects, list):
1096 if isinstance(o, Mesh):
1097 srclist.append(o.mesh)
1098 elif hasattr(o, "_narrow"):
1099 src = o._narrow(SMESH.SMESH_IDSource)
1100 if src: srclist.append(src)
1103 aMeasurements = self.CreateMeasurements()
1104 result = aMeasurements.BoundingBox(srclist)
1105 aMeasurements.UnRegister()
1108 ## Get sum of lengths of all 1D elements in the mesh object.
1109 # @param obj mesh, submesh or group
1110 # @return sum of lengths of all 1D elements
1111 # @ingroup l1_measurements
1112 def GetLength(self, obj):
1113 if isinstance(obj, Mesh): obj = obj.mesh
1114 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1115 aMeasurements = self.CreateMeasurements()
1116 value = aMeasurements.Length(obj)
1117 aMeasurements.UnRegister()
1120 ## Get sum of areas of all 2D elements in the mesh object.
1121 # @param obj mesh, submesh or group
1122 # @return sum of areas of all 2D elements
1123 # @ingroup l1_measurements
1124 def GetArea(self, obj):
1125 if isinstance(obj, Mesh): obj = obj.mesh
1126 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1127 aMeasurements = self.CreateMeasurements()
1128 value = aMeasurements.Area(obj)
1129 aMeasurements.UnRegister()
1132 ## Get sum of volumes of all 3D elements in the mesh object.
1133 # @param obj mesh, submesh or group
1134 # @return sum of volumes of all 3D elements
1135 # @ingroup l1_measurements
1136 def GetVolume(self, obj):
1137 if isinstance(obj, Mesh): obj = obj.mesh
1138 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1139 aMeasurements = self.CreateMeasurements()
1140 value = aMeasurements.Volume(obj)
1141 aMeasurements.UnRegister()
1144 pass # end of class smeshBuilder
1147 #Registering the new proxy for SMESH_Gen
1148 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1150 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1151 # interface to create or load meshes.
1156 # salome.salome_init()
1157 # from salome.smesh import smeshBuilder
1158 # smesh = smeshBuilder.New()
1160 # @param isPublished If False, the notebool will not be used.
1161 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1162 # @return smeshBuilder instance
1164 def New( isPublished = True, instance=None):
1166 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1167 interface to create or load meshes.
1171 salome.salome_init()
1172 from salome.smesh import smeshBuilder
1173 smesh = smeshBuilder.New()
1176 isPublished If False, the notebool will not be used.
1177 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1179 smeshBuilder instance
1187 smeshInst = smeshBuilder()
1188 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1189 smeshInst.init_smesh(isPublished)
1193 # Public class: Mesh
1194 # ==================
1196 ## This class allows defining and managing a mesh.
1197 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1198 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1199 # new nodes and elements and by changing the existing entities), to get information
1200 # about a mesh and to export a mesh in different formats.
1202 __metaclass__ = MeshMeta
1210 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1211 # sets the GUI name of this mesh to \a name.
1212 # @param smeshpyD an instance of smeshBuilder class
1213 # @param geompyD an instance of geomBuilder class
1214 # @param obj Shape to be meshed or SMESH_Mesh object
1215 # @param name Study name of the mesh
1216 # @ingroup l2_construct
1217 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1218 self.smeshpyD=smeshpyD
1219 self.geompyD=geompyD
1224 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1227 # publish geom of mesh (issue 0021122)
1228 if not self.geom.GetStudyEntry():
1232 geo_name = name + " shape"
1234 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1235 geompyD.addToStudy( self.geom, geo_name )
1236 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1238 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1241 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1243 self.smeshpyD.SetName(self.mesh, name)
1245 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1248 self.geom = self.mesh.GetShapeToMesh()
1250 self.editor = self.mesh.GetMeshEditor()
1251 self.functors = [None] * SMESH.FT_Undefined._v
1253 # set self to algoCreator's
1254 for attrName in dir(self):
1255 attr = getattr( self, attrName )
1256 if isinstance( attr, algoCreator ):
1257 setattr( self, attrName, attr.copy( self ))
1262 ## Destructor. Clean-up resources
1265 #self.mesh.UnRegister()
1269 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1270 # @param theMesh a SMESH_Mesh object
1271 # @ingroup l2_construct
1272 def SetMesh(self, theMesh):
1273 # do not call Register() as this prevents mesh servant deletion at closing study
1274 #if self.mesh: self.mesh.UnRegister()
1277 #self.mesh.Register()
1278 self.geom = self.mesh.GetShapeToMesh()
1281 ## Return the mesh, that is an instance of SMESH_Mesh interface
1282 # @return a SMESH_Mesh object
1283 # @ingroup l2_construct
1287 ## Get the name of the mesh
1288 # @return the name of the mesh as a string
1289 # @ingroup l2_construct
1291 name = GetName(self.GetMesh())
1294 ## Set a name to the mesh
1295 # @param name a new name of the mesh
1296 # @ingroup l2_construct
1297 def SetName(self, name):
1298 self.smeshpyD.SetName(self.GetMesh(), name)
1300 ## Get a sub-mesh object associated to a \a geom geometrical object.
1301 # @param geom a geometrical object (shape)
1302 # @param name a name for the sub-mesh in the Object Browser
1303 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1304 # which lies on the given shape
1306 # The sub-mesh object gives access to the IDs of nodes and elements.
1307 # The sub-mesh object has the following methods:
1308 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1309 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1310 # - SMESH.SMESH_subMesh.GetElementsId()
1311 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1312 # - SMESH.SMESH_subMesh.GetNodesId()
1313 # - SMESH.SMESH_subMesh.GetSubShape()
1314 # - SMESH.SMESH_subMesh.GetFather()
1315 # - SMESH.SMESH_subMesh.GetId()
1316 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1317 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1318 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1319 # The created sub-mesh can be retrieved from the algorithm:
1320 # <code>submesh = algo1D.GetSubMesh()</code>
1321 # @ingroup l2_submeshes
1322 def GetSubMesh(self, geom, name):
1323 AssureGeomPublished( self, geom, name )
1324 submesh = self.mesh.GetSubMesh( geom, name )
1327 ## Return the shape associated to the mesh
1328 # @return a GEOM_Object
1329 # @ingroup l2_construct
1333 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1334 # @param geom the shape to be meshed (GEOM_Object)
1335 # @ingroup l2_construct
1336 def SetShape(self, geom):
1337 self.mesh = self.smeshpyD.CreateMesh(geom)
1339 ## Load mesh from the study after opening the study
1343 ## Return true if the hypotheses are defined well
1344 # @param theSubObject a sub-shape of a mesh shape
1345 # @return True or False
1346 # @ingroup l2_construct
1347 def IsReadyToCompute(self, theSubObject):
1348 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1350 ## Return errors of hypotheses definition.
1351 # The list of errors is empty if everything is OK.
1352 # @param theSubObject a sub-shape of a mesh shape
1353 # @return a list of errors
1354 # @ingroup l2_construct
1355 def GetAlgoState(self, theSubObject):
1356 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1358 ## Return a geometrical object on which the given element was built.
1359 # The returned geometrical object, if not nil, is either found in the
1360 # study or published by this method with the given name
1361 # @param theElementID the id of the mesh element
1362 # @param theGeomName the user-defined name of the geometrical object
1363 # @return GEOM::GEOM_Object instance
1364 # @ingroup l1_meshinfo
1365 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1366 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1368 ## Return the mesh dimension depending on the dimension of the underlying shape
1369 # or, if the mesh is not based on any shape, basing on deimension of elements
1370 # @return mesh dimension as an integer value [0,3]
1371 # @ingroup l1_meshinfo
1372 def MeshDimension(self):
1373 if self.mesh.HasShapeToMesh():
1374 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1375 if len( shells ) > 0 :
1377 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1379 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1384 if self.NbVolumes() > 0: return 3
1385 if self.NbFaces() > 0: return 2
1386 if self.NbEdges() > 0: return 1
1389 ## Evaluate size of prospective mesh on a shape
1390 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1391 # To know predicted number of e.g. edges, inquire it this way
1392 # Evaluate()[ EnumToLong( Entity_Edge )]
1393 # @ingroup l2_construct
1394 def Evaluate(self, geom=0):
1395 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1397 geom = self.mesh.GetShapeToMesh()
1400 return self.smeshpyD.Evaluate(self.mesh, geom)
1403 ## Compute the mesh and return the status of the computation
1404 # @param geom geomtrical shape on which mesh data should be computed
1405 # @param discardModifs if True and the mesh has been edited since
1406 # a last total re-compute and that may prevent successful partial re-compute,
1407 # then the mesh is cleaned before Compute()
1408 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1409 # @return True or False
1410 # @ingroup l2_construct
1411 def Compute(self, geom=0, discardModifs=False, refresh=False):
1412 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1414 geom = self.mesh.GetShapeToMesh()
1419 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1421 ok = self.smeshpyD.Compute(self.mesh, geom)
1422 except SALOME.SALOME_Exception, ex:
1423 print "Mesh computation failed, exception caught:"
1424 print " ", ex.details.text
1427 print "Mesh computation failed, exception caught:"
1428 traceback.print_exc()
1432 # Treat compute errors
1433 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1435 for err in computeErrors:
1436 if self.mesh.HasShapeToMesh():
1437 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1439 stdErrors = ["OK", #COMPERR_OK
1440 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1441 "std::exception", #COMPERR_STD_EXCEPTION
1442 "OCC exception", #COMPERR_OCC_EXCEPTION
1443 "..", #COMPERR_SLM_EXCEPTION
1444 "Unknown exception", #COMPERR_EXCEPTION
1445 "Memory allocation problem", #COMPERR_MEMORY_PB
1446 "Algorithm failed", #COMPERR_ALGO_FAILED
1447 "Unexpected geometry", #COMPERR_BAD_SHAPE
1448 "Warning", #COMPERR_WARNING
1449 "Computation cancelled",#COMPERR_CANCELED
1450 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1452 if err.code < len(stdErrors): errText = stdErrors[err.code]
1454 errText = "code %s" % -err.code
1455 if errText: errText += ". "
1456 errText += err.comment
1457 if allReasons: allReasons += "\n"
1459 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1461 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1465 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1467 if err.isGlobalAlgo:
1475 reason = '%s %sD algorithm is missing' % (glob, dim)
1476 elif err.state == HYP_MISSING:
1477 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1478 % (glob, dim, name, dim))
1479 elif err.state == HYP_NOTCONFORM:
1480 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1481 elif err.state == HYP_BAD_PARAMETER:
1482 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1483 % ( glob, dim, name ))
1484 elif err.state == HYP_BAD_GEOMETRY:
1485 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1486 'geometry' % ( glob, dim, name ))
1487 elif err.state == HYP_HIDDEN_ALGO:
1488 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1489 'algorithm of upper dimension generating %sD mesh'
1490 % ( glob, dim, name, glob, dim ))
1492 reason = ("For unknown reason. "
1493 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1495 if allReasons: allReasons += "\n"
1496 allReasons += "- " + reason
1498 if not ok or allReasons != "":
1499 msg = '"' + GetName(self.mesh) + '"'
1500 if ok: msg += " has been computed with warnings"
1501 else: msg += " has not been computed"
1502 if allReasons != "": msg += ":"
1507 if salome.sg.hasDesktop():
1508 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1509 smeshgui = salome.ImportComponentGUI("SMESH")
1511 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1512 if refresh: salome.sg.updateObjBrowser()
1516 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1517 # @ingroup l2_construct
1518 def GetComputeErrors(self, shape=0 ):
1520 shape = self.mesh.GetShapeToMesh()
1521 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1523 ## Return a name of a sub-shape by its ID
1524 # @param subShapeID a unique ID of a sub-shape
1525 # @return a string describing the sub-shape; possible variants:
1526 # - "Face_12" (published sub-shape)
1527 # - FACE #3 (not published sub-shape)
1528 # - sub-shape #3 (invalid sub-shape ID)
1529 # - #3 (error in this function)
1530 # @ingroup l1_auxiliary
1531 def GetSubShapeName(self, subShapeID ):
1532 if not self.mesh.HasShapeToMesh():
1536 mainIOR = salome.orb.object_to_string( self.GetShape() )
1538 mainSO = s.FindObjectIOR(mainIOR)
1541 shapeText = '"%s"' % mainSO.GetName()
1542 subIt = s.NewChildIterator(mainSO)
1544 subSO = subIt.Value()
1546 obj = subSO.GetObject()
1547 if not obj: continue
1548 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1551 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1554 if ids == subShapeID:
1555 shapeText = '"%s"' % subSO.GetName()
1557 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1559 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1561 shapeText = 'sub-shape #%s' % (subShapeID)
1563 shapeText = "#%s" % (subShapeID)
1566 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1567 # error of an algorithm
1568 # @param publish if @c True, the returned groups will be published in the study
1569 # @return a list of GEOM groups each named after a failed algorithm
1570 # @ingroup l2_construct
1571 def GetFailedShapes(self, publish=False):
1574 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1575 for err in computeErrors:
1576 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1577 if not shape: continue
1578 if err.algoName in algo2shapes:
1579 algo2shapes[ err.algoName ].append( shape )
1581 algo2shapes[ err.algoName ] = [ shape ]
1585 for algoName, shapes in algo2shapes.items():
1587 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1588 otherTypeShapes = []
1590 group = self.geompyD.CreateGroup( self.geom, groupType )
1591 for shape in shapes:
1592 if shape.GetShapeType() == shapes[0].GetShapeType():
1593 sameTypeShapes.append( shape )
1595 otherTypeShapes.append( shape )
1596 self.geompyD.UnionList( group, sameTypeShapes )
1598 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1600 group.SetName( algoName )
1601 groups.append( group )
1602 shapes = otherTypeShapes
1605 for group in groups:
1606 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1609 ## Return sub-mesh objects list in meshing order
1610 # @return list of lists of sub-meshes
1611 # @ingroup l2_construct
1612 def GetMeshOrder(self):
1613 return self.mesh.GetMeshOrder()
1615 ## Set order in which concurrent sub-meshes should be meshed
1616 # @param submeshes list of lists of sub-meshes
1617 # @ingroup l2_construct
1618 def SetMeshOrder(self, submeshes):
1619 return self.mesh.SetMeshOrder(submeshes)
1621 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1622 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1623 # @ingroup l2_construct
1624 def Clear(self, refresh=False):
1626 if ( salome.sg.hasDesktop() ):
1627 smeshgui = salome.ImportComponentGUI("SMESH")
1629 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1630 if refresh: salome.sg.updateObjBrowser()
1632 ## Remove all nodes and elements of indicated shape
1633 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1634 # @param geomId the ID of a sub-shape to remove elements on
1635 # @ingroup l2_submeshes
1636 def ClearSubMesh(self, geomId, refresh=False):
1637 self.mesh.ClearSubMesh(geomId)
1638 if salome.sg.hasDesktop():
1639 smeshgui = salome.ImportComponentGUI("SMESH")
1641 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1642 if refresh: salome.sg.updateObjBrowser()
1644 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1645 # @param fineness [0.0,1.0] defines mesh fineness
1646 # @return True or False
1647 # @ingroup l3_algos_basic
1648 def AutomaticTetrahedralization(self, fineness=0):
1649 dim = self.MeshDimension()
1651 self.RemoveGlobalHypotheses()
1652 self.Segment().AutomaticLength(fineness)
1654 self.Triangle().LengthFromEdges()
1659 return self.Compute()
1661 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1662 # @param fineness [0.0, 1.0] defines mesh fineness
1663 # @return True or False
1664 # @ingroup l3_algos_basic
1665 def AutomaticHexahedralization(self, fineness=0):
1666 dim = self.MeshDimension()
1667 # assign the hypotheses
1668 self.RemoveGlobalHypotheses()
1669 self.Segment().AutomaticLength(fineness)
1676 return self.Compute()
1678 ## Assign a hypothesis
1679 # @param hyp a hypothesis to assign
1680 # @param geom a subhape of mesh geometry
1681 # @return SMESH.Hypothesis_Status
1682 # @ingroup l2_editing
1683 def AddHypothesis(self, hyp, geom=0):
1684 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1685 hyp, geom = geom, hyp
1686 if isinstance( hyp, Mesh_Algorithm ):
1687 hyp = hyp.GetAlgorithm()
1692 geom = self.mesh.GetShapeToMesh()
1695 if self.mesh.HasShapeToMesh():
1696 hyp_type = hyp.GetName()
1697 lib_name = hyp.GetLibName()
1698 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1699 # if checkAll and geom:
1700 # checkAll = geom.GetType() == 37
1702 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1704 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1705 status = self.mesh.AddHypothesis(geom, hyp)
1707 status = HYP_BAD_GEOMETRY,""
1708 hyp_name = GetName( hyp )
1711 geom_name = geom.GetName()
1712 isAlgo = hyp._narrow( SMESH_Algo )
1713 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1716 ## Return True if an algorithm of hypothesis is assigned to a given shape
1717 # @param hyp a hypothesis to check
1718 # @param geom a subhape of mesh geometry
1719 # @return True of False
1720 # @ingroup l2_editing
1721 def IsUsedHypothesis(self, hyp, geom):
1722 if not hyp: # or not geom
1724 if isinstance( hyp, Mesh_Algorithm ):
1725 hyp = hyp.GetAlgorithm()
1727 hyps = self.GetHypothesisList(geom)
1729 if h.GetId() == hyp.GetId():
1733 ## Unassign a hypothesis
1734 # @param hyp a hypothesis to unassign
1735 # @param geom a sub-shape of mesh geometry
1736 # @return SMESH.Hypothesis_Status
1737 # @ingroup l2_editing
1738 def RemoveHypothesis(self, hyp, geom=0):
1741 if isinstance( hyp, Mesh_Algorithm ):
1742 hyp = hyp.GetAlgorithm()
1748 if self.IsUsedHypothesis( hyp, shape ):
1749 return self.mesh.RemoveHypothesis( shape, hyp )
1750 hypName = GetName( hyp )
1751 geoName = GetName( shape )
1752 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1755 ## Get the list of hypotheses added on a geometry
1756 # @param geom a sub-shape of mesh geometry
1757 # @return the sequence of SMESH_Hypothesis
1758 # @ingroup l2_editing
1759 def GetHypothesisList(self, geom):
1760 return self.mesh.GetHypothesisList( geom )
1762 ## Remove all global hypotheses
1763 # @ingroup l2_editing
1764 def RemoveGlobalHypotheses(self):
1765 current_hyps = self.mesh.GetHypothesisList( self.geom )
1766 for hyp in current_hyps:
1767 self.mesh.RemoveHypothesis( self.geom, hyp )
1771 ## Export the mesh in a file in MED format
1772 ## allowing to overwrite the file if it exists or add the exported data to its contents
1773 # @param f is the file name
1774 # @param auto_groups boolean parameter for creating/not creating
1775 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1776 # the typical use is auto_groups=False.
1777 # @param version MED format version (MED_V2_1 or MED_V2_2,
1778 # the latter meaning any current version). The parameter is
1779 # obsolete since MED_V2_1 is no longer supported.
1780 # @param overwrite boolean parameter for overwriting/not overwriting the file
1781 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1782 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1783 # - 1D if all mesh nodes lie on OX coordinate axis, or
1784 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1785 # - 3D in the rest cases.<br>
1786 # If @a autoDimension is @c False, the space dimension is always 3.
1787 # @param fields list of GEOM fields defined on the shape to mesh.
1788 # @param geomAssocFields each character of this string means a need to export a
1789 # corresponding field; correspondence between fields and characters is following:
1790 # - 'v' stands for "_vertices _" field;
1791 # - 'e' stands for "_edges _" field;
1792 # - 'f' stands for "_faces _" field;
1793 # - 's' stands for "_solids _" field.
1794 # @ingroup l2_impexp
1795 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1796 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1797 if meshPart or fields or geomAssocFields:
1798 unRegister = genObjUnRegister()
1799 if isinstance( meshPart, list ):
1800 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1801 unRegister.set( meshPart )
1802 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1803 fields, geomAssocFields)
1805 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1807 ## Export the mesh in a file in SAUV format
1808 # @param f is the file name
1809 # @param auto_groups boolean parameter for creating/not creating
1810 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1811 # the typical use is auto_groups=false.
1812 # @ingroup l2_impexp
1813 def ExportSAUV(self, f, auto_groups=0):
1814 self.mesh.ExportSAUV(f, auto_groups)
1816 ## Export the mesh in a file in DAT format
1817 # @param f the file name
1818 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1819 # @ingroup l2_impexp
1820 def ExportDAT(self, f, meshPart=None):
1822 unRegister = genObjUnRegister()
1823 if isinstance( meshPart, list ):
1824 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1825 unRegister.set( meshPart )
1826 self.mesh.ExportPartToDAT( meshPart, f )
1828 self.mesh.ExportDAT(f)
1830 ## Export the mesh in a file in UNV format
1831 # @param f the file name
1832 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1833 # @ingroup l2_impexp
1834 def ExportUNV(self, f, meshPart=None):
1836 unRegister = genObjUnRegister()
1837 if isinstance( meshPart, list ):
1838 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1839 unRegister.set( meshPart )
1840 self.mesh.ExportPartToUNV( meshPart, f )
1842 self.mesh.ExportUNV(f)
1844 ## Export the mesh in a file in STL format
1845 # @param f the file name
1846 # @param ascii defines the file encoding
1847 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1848 # @ingroup l2_impexp
1849 def ExportSTL(self, f, ascii=1, meshPart=None):
1851 unRegister = genObjUnRegister()
1852 if isinstance( meshPart, list ):
1853 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1854 unRegister.set( meshPart )
1855 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1857 self.mesh.ExportSTL(f, ascii)
1859 ## Export the mesh in a file in CGNS format
1860 # @param f is the file name
1861 # @param overwrite boolean parameter for overwriting/not overwriting the file
1862 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1863 # @ingroup l2_impexp
1864 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1865 unRegister = genObjUnRegister()
1866 if isinstance( meshPart, list ):
1867 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1868 unRegister.set( meshPart )
1869 if isinstance( meshPart, Mesh ):
1870 meshPart = meshPart.mesh
1872 meshPart = self.mesh
1873 self.mesh.ExportCGNS(meshPart, f, overwrite)
1875 ## Export the mesh in a file in GMF format.
1876 # GMF files must have .mesh extension for the ASCII format and .meshb for
1877 # the bynary format. Other extensions are not allowed.
1878 # @param f is the file name
1879 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1880 # @ingroup l2_impexp
1881 def ExportGMF(self, f, meshPart=None):
1882 unRegister = genObjUnRegister()
1883 if isinstance( meshPart, list ):
1884 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1885 unRegister.set( meshPart )
1886 if isinstance( meshPart, Mesh ):
1887 meshPart = meshPart.mesh
1889 meshPart = self.mesh
1890 self.mesh.ExportGMF(meshPart, f, True)
1892 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1893 # Export the mesh in a file in MED format
1894 # allowing to overwrite the file if it exists or add the exported data to its contents
1895 # @param f the file name
1896 # @param version MED format version (MED_V2_1 or MED_V2_2,
1897 # the latter meaning any current version). The parameter is
1898 # obsolete since MED_V2_1 is no longer supported.
1899 # @param opt boolean parameter for creating/not creating
1900 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1901 # @param overwrite boolean parameter for overwriting/not overwriting the file
1902 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1903 # - 1D if all mesh nodes lie on OX coordinate axis, or
1904 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1905 # - 3D in the rest cases.<br>
1906 # If @a autoDimension is @c False, the space dimension is always 3.
1907 # @ingroup l2_impexp
1908 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
1909 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1911 # Operations with groups:
1912 # ----------------------
1914 ## Create an empty mesh group
1915 # @param elementType the type of elements in the group; either of
1916 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1917 # @param name the name of the mesh group
1918 # @return SMESH_Group
1919 # @ingroup l2_grps_create
1920 def CreateEmptyGroup(self, elementType, name):
1921 return self.mesh.CreateGroup(elementType, name)
1923 ## Create a mesh group based on the geometric object \a grp
1924 # and gives a \a name, \n if this parameter is not defined
1925 # the name is the same as the geometric group name \n
1926 # Note: Works like GroupOnGeom().
1927 # @param grp a geometric group, a vertex, an edge, a face or a solid
1928 # @param name the name of the mesh group
1929 # @return SMESH_GroupOnGeom
1930 # @ingroup l2_grps_create
1931 def Group(self, grp, name=""):
1932 return self.GroupOnGeom(grp, name)
1934 ## Create a mesh group based on the geometrical object \a grp
1935 # and gives a \a name, \n if this parameter is not defined
1936 # the name is the same as the geometrical group name
1937 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1938 # @param name the name of the mesh group
1939 # @param typ the type of elements in the group; either of
1940 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1941 # automatically detected by the type of the geometry
1942 # @return SMESH_GroupOnGeom
1943 # @ingroup l2_grps_create
1944 def GroupOnGeom(self, grp, name="", typ=None):
1945 AssureGeomPublished( self, grp, name )
1947 name = grp.GetName()
1949 typ = self._groupTypeFromShape( grp )
1950 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1952 ## Pivate method to get a type of group on geometry
1953 def _groupTypeFromShape( self, shape ):
1954 tgeo = str(shape.GetShapeType())
1955 if tgeo == "VERTEX":
1957 elif tgeo == "EDGE":
1959 elif tgeo == "FACE" or tgeo == "SHELL":
1961 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1963 elif tgeo == "COMPOUND":
1964 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1966 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1967 return self._groupTypeFromShape( sub[0] )
1970 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1973 ## Create a mesh group with given \a name based on the \a filter which
1974 ## is a special type of group dynamically updating it's contents during
1975 ## mesh modification
1976 # @param typ the type of elements in the group; either of
1977 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1978 # @param name the name of the mesh group
1979 # @param filter the filter defining group contents
1980 # @return SMESH_GroupOnFilter
1981 # @ingroup l2_grps_create
1982 def GroupOnFilter(self, typ, name, filter):
1983 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1985 ## Create a mesh group by the given ids of elements
1986 # @param groupName the name of the mesh group
1987 # @param elementType the type of elements in the group; either of
1988 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1989 # @param elemIDs either the list of ids, group, sub-mesh, or filter
1990 # @return SMESH_Group
1991 # @ingroup l2_grps_create
1992 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1993 group = self.mesh.CreateGroup(elementType, groupName)
1994 if hasattr( elemIDs, "GetIDs" ):
1995 if hasattr( elemIDs, "SetMesh" ):
1996 elemIDs.SetMesh( self.GetMesh() )
1997 group.AddFrom( elemIDs )
2002 ## Create a mesh group by the given conditions
2003 # @param groupName the name of the mesh group
2004 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2005 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2006 # Type SMESH.FunctorType._items in the Python Console to see all values.
2007 # Note that the items starting from FT_LessThan are not suitable for CritType.
2008 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2009 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2010 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2011 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2012 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2013 # @return SMESH_GroupOnFilter
2014 # @ingroup l2_grps_create
2018 CritType=FT_Undefined,
2021 UnaryOp=FT_Undefined,
2023 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2024 group = self.MakeGroupByCriterion(groupName, aCriterion)
2027 ## Create a mesh group by the given criterion
2028 # @param groupName the name of the mesh group
2029 # @param Criterion the instance of Criterion class
2030 # @return SMESH_GroupOnFilter
2031 # @ingroup l2_grps_create
2032 def MakeGroupByCriterion(self, groupName, Criterion):
2033 return self.MakeGroupByCriteria( groupName, [Criterion] )
2035 ## Create a mesh group by the given criteria (list of criteria)
2036 # @param groupName the name of the mesh group
2037 # @param theCriteria the list of criteria
2038 # @param binOp binary operator used when binary operator of criteria is undefined
2039 # @return SMESH_GroupOnFilter
2040 # @ingroup l2_grps_create
2041 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2042 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2043 group = self.MakeGroupByFilter(groupName, aFilter)
2046 ## Create a mesh group by the given filter
2047 # @param groupName the name of the mesh group
2048 # @param theFilter the instance of Filter class
2049 # @return SMESH_GroupOnFilter
2050 # @ingroup l2_grps_create
2051 def MakeGroupByFilter(self, groupName, theFilter):
2052 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2053 #theFilter.SetMesh( self.mesh )
2054 #group.AddFrom( theFilter )
2055 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2059 # @ingroup l2_grps_delete
2060 def RemoveGroup(self, group):
2061 self.mesh.RemoveGroup(group)
2063 ## Remove a group with its contents
2064 # @ingroup l2_grps_delete
2065 def RemoveGroupWithContents(self, group):
2066 self.mesh.RemoveGroupWithContents(group)
2068 ## Get the list of groups existing in the mesh in the order
2069 # of creation (starting from the oldest one)
2070 # @param elemType type of elements the groups contain; either of
2071 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2072 # by default groups of elements of all types are returned
2073 # @return a sequence of SMESH_GroupBase
2074 # @ingroup l2_grps_create
2075 def GetGroups(self, elemType = SMESH.ALL):
2076 groups = self.mesh.GetGroups()
2077 if elemType == SMESH.ALL:
2081 if g.GetType() == elemType:
2082 typedGroups.append( g )
2087 ## Get the number of groups existing in the mesh
2088 # @return the quantity of groups as an integer value
2089 # @ingroup l2_grps_create
2091 return self.mesh.NbGroups()
2093 ## Get the list of names of groups existing in the mesh
2094 # @return list of strings
2095 # @ingroup l2_grps_create
2096 def GetGroupNames(self):
2097 groups = self.GetGroups()
2099 for group in groups:
2100 names.append(group.GetName())
2103 ## Find groups by name and type
2104 # @param name name of the group of interest
2105 # @param elemType type of elements the groups contain; either of
2106 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2107 # by default one group of any type of elements is returned
2108 # if elemType == SMESH.ALL then all groups of any type are returned
2109 # @return a list of SMESH_GroupBase's
2110 # @ingroup l2_grps_create
2111 def GetGroupByName(self, name, elemType = None):
2113 for group in self.GetGroups():
2114 if group.GetName() == name:
2115 if elemType is None:
2117 if ( elemType == SMESH.ALL or
2118 group.GetType() == elemType ):
2119 groups.append( group )
2122 ## Produce a union of two groups.
2123 # A new group is created. All mesh elements that are
2124 # present in the initial groups are added to the new one
2125 # @return an instance of SMESH_Group
2126 # @ingroup l2_grps_operon
2127 def UnionGroups(self, group1, group2, name):
2128 return self.mesh.UnionGroups(group1, group2, name)
2130 ## Produce a union list of groups.
2131 # New group is created. All mesh elements that are present in
2132 # initial groups are added to the new one
2133 # @return an instance of SMESH_Group
2134 # @ingroup l2_grps_operon
2135 def UnionListOfGroups(self, groups, name):
2136 return self.mesh.UnionListOfGroups(groups, name)
2138 ## Prodice an intersection of two groups.
2139 # A new group is created. All mesh elements that are common
2140 # for the two initial groups are added to the new one.
2141 # @return an instance of SMESH_Group
2142 # @ingroup l2_grps_operon
2143 def IntersectGroups(self, group1, group2, name):
2144 return self.mesh.IntersectGroups(group1, group2, name)
2146 ## Produce an intersection of groups.
2147 # New group is created. All mesh elements that are present in all
2148 # initial groups simultaneously are added to the new one
2149 # @return an instance of SMESH_Group
2150 # @ingroup l2_grps_operon
2151 def IntersectListOfGroups(self, groups, name):
2152 return self.mesh.IntersectListOfGroups(groups, name)
2154 ## Produce a cut of two groups.
2155 # A new group is created. All mesh elements that are present in
2156 # the main group but are not present in the tool group are added to the new one
2157 # @return an instance of SMESH_Group
2158 # @ingroup l2_grps_operon
2159 def CutGroups(self, main_group, tool_group, name):
2160 return self.mesh.CutGroups(main_group, tool_group, name)
2162 ## Produce a cut of groups.
2163 # A new group is created. All mesh elements that are present in main groups
2164 # but do not present in tool groups are added to the new one
2165 # @return an instance of SMESH_Group
2166 # @ingroup l2_grps_operon
2167 def CutListOfGroups(self, main_groups, tool_groups, name):
2168 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2171 # Create a standalone group of entities basing on nodes of other groups.
2172 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2173 # \param elemType - a type of elements to include to the new group; either of
2174 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2175 # \param name - a name of the new group.
2176 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2177 # basing on number of element nodes common with reference \a groups.
2178 # Meaning of possible values are:
2179 # - SMESH.ALL_NODES - include if all nodes are common,
2180 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2181 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2182 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2183 # \param underlyingOnly - if \c True (default), an element is included to the
2184 # new group provided that it is based on nodes of an element of \a groups;
2185 # in this case the reference \a groups are supposed to be of higher dimension
2186 # than \a elemType, which can be useful for example to get all faces lying on
2187 # volumes of the reference \a groups.
2188 # @return an instance of SMESH_Group
2189 # @ingroup l2_grps_operon
2190 def CreateDimGroup(self, groups, elemType, name,
2191 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2192 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2194 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2197 ## Convert group on geom into standalone group
2198 # @ingroup l2_grps_operon
2199 def ConvertToStandalone(self, group):
2200 return self.mesh.ConvertToStandalone(group)
2202 # Get some info about mesh:
2203 # ------------------------
2205 ## Return the log of nodes and elements added or removed
2206 # since the previous clear of the log.
2207 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2208 # @return list of log_block structures:
2213 # @ingroup l1_auxiliary
2214 def GetLog(self, clearAfterGet):
2215 return self.mesh.GetLog(clearAfterGet)
2217 ## Clear the log of nodes and elements added or removed since the previous
2218 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2219 # @ingroup l1_auxiliary
2221 self.mesh.ClearLog()
2223 ## Toggle auto color mode on the object.
2224 # @param theAutoColor the flag which toggles auto color mode.
2226 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2227 # @ingroup l1_grouping
2228 def SetAutoColor(self, theAutoColor):
2229 self.mesh.SetAutoColor(theAutoColor)
2231 ## Get flag of object auto color mode.
2232 # @return True or False
2233 # @ingroup l1_grouping
2234 def GetAutoColor(self):
2235 return self.mesh.GetAutoColor()
2237 ## Get the internal ID
2238 # @return integer value, which is the internal Id of the mesh
2239 # @ingroup l1_auxiliary
2241 return self.mesh.GetId()
2243 ## Check the group names for duplications.
2244 # Consider the maximum group name length stored in MED file.
2245 # @return True or False
2246 # @ingroup l1_grouping
2247 def HasDuplicatedGroupNamesMED(self):
2248 return self.mesh.HasDuplicatedGroupNamesMED()
2250 ## Obtain the mesh editor tool
2251 # @return an instance of SMESH_MeshEditor
2252 # @ingroup l1_modifying
2253 def GetMeshEditor(self):
2256 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2257 # can be passed as argument to a method accepting mesh, group or sub-mesh
2258 # @param ids list of IDs
2259 # @param elemType type of elements; this parameter is used to distinguish
2260 # IDs of nodes from IDs of elements; by default ids are treated as
2261 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2262 # @return an instance of SMESH_IDSource
2263 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2264 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2265 # mesh.DoSomething( idSrc )
2266 # idSrc.UnRegister()
2267 # @ingroup l1_auxiliary
2268 def GetIDSource(self, ids, elemType = SMESH.ALL):
2269 if isinstance( ids, int ):
2271 return self.editor.MakeIDSource(ids, elemType)
2274 # Get informations about mesh contents:
2275 # ------------------------------------
2277 ## Get the mesh stattistic
2278 # @return dictionary type element - count of elements
2279 # @ingroup l1_meshinfo
2280 def GetMeshInfo(self, obj = None):
2281 if not obj: obj = self.mesh
2282 return self.smeshpyD.GetMeshInfo(obj)
2284 ## Return the number of nodes in the mesh
2285 # @return an integer value
2286 # @ingroup l1_meshinfo
2288 return self.mesh.NbNodes()
2290 ## Return the number of elements in the mesh
2291 # @return an integer value
2292 # @ingroup l1_meshinfo
2293 def NbElements(self):
2294 return self.mesh.NbElements()
2296 ## Return the number of 0d elements in the mesh
2297 # @return an integer value
2298 # @ingroup l1_meshinfo
2299 def Nb0DElements(self):
2300 return self.mesh.Nb0DElements()
2302 ## Return the number of ball discrete elements in the mesh
2303 # @return an integer value
2304 # @ingroup l1_meshinfo
2306 return self.mesh.NbBalls()
2308 ## Return the number of edges in the mesh
2309 # @return an integer value
2310 # @ingroup l1_meshinfo
2312 return self.mesh.NbEdges()
2314 ## Return the number of edges with the given order in the mesh
2315 # @param elementOrder the order of elements:
2316 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2317 # @return an integer value
2318 # @ingroup l1_meshinfo
2319 def NbEdgesOfOrder(self, elementOrder):
2320 return self.mesh.NbEdgesOfOrder(elementOrder)
2322 ## Return the number of faces in the mesh
2323 # @return an integer value
2324 # @ingroup l1_meshinfo
2326 return self.mesh.NbFaces()
2328 ## Return the number of faces with the given order in the mesh
2329 # @param elementOrder the order of elements:
2330 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2331 # @return an integer value
2332 # @ingroup l1_meshinfo
2333 def NbFacesOfOrder(self, elementOrder):
2334 return self.mesh.NbFacesOfOrder(elementOrder)
2336 ## Return the number of triangles in the mesh
2337 # @return an integer value
2338 # @ingroup l1_meshinfo
2339 def NbTriangles(self):
2340 return self.mesh.NbTriangles()
2342 ## Return the number of triangles with the given order in the mesh
2343 # @param elementOrder is the order of elements:
2344 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2345 # @return an integer value
2346 # @ingroup l1_meshinfo
2347 def NbTrianglesOfOrder(self, elementOrder):
2348 return self.mesh.NbTrianglesOfOrder(elementOrder)
2350 ## Return the number of biquadratic triangles in the mesh
2351 # @return an integer value
2352 # @ingroup l1_meshinfo
2353 def NbBiQuadTriangles(self):
2354 return self.mesh.NbBiQuadTriangles()
2356 ## Return the number of quadrangles in the mesh
2357 # @return an integer value
2358 # @ingroup l1_meshinfo
2359 def NbQuadrangles(self):
2360 return self.mesh.NbQuadrangles()
2362 ## Return the number of quadrangles with the given order in the mesh
2363 # @param elementOrder the order of elements:
2364 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2365 # @return an integer value
2366 # @ingroup l1_meshinfo
2367 def NbQuadranglesOfOrder(self, elementOrder):
2368 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2370 ## Return the number of biquadratic quadrangles in the mesh
2371 # @return an integer value
2372 # @ingroup l1_meshinfo
2373 def NbBiQuadQuadrangles(self):
2374 return self.mesh.NbBiQuadQuadrangles()
2376 ## Return the number of polygons of given order in the mesh
2377 # @param elementOrder the order of elements:
2378 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2379 # @return an integer value
2380 # @ingroup l1_meshinfo
2381 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2382 return self.mesh.NbPolygonsOfOrder(elementOrder)
2384 ## Return the number of volumes in the mesh
2385 # @return an integer value
2386 # @ingroup l1_meshinfo
2387 def NbVolumes(self):
2388 return self.mesh.NbVolumes()
2390 ## Return the number of volumes with the given order in the mesh
2391 # @param elementOrder the order of elements:
2392 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2393 # @return an integer value
2394 # @ingroup l1_meshinfo
2395 def NbVolumesOfOrder(self, elementOrder):
2396 return self.mesh.NbVolumesOfOrder(elementOrder)
2398 ## Return the number of tetrahedrons in the mesh
2399 # @return an integer value
2400 # @ingroup l1_meshinfo
2402 return self.mesh.NbTetras()
2404 ## Return the number of tetrahedrons with the given order in the mesh
2405 # @param elementOrder the order of elements:
2406 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2407 # @return an integer value
2408 # @ingroup l1_meshinfo
2409 def NbTetrasOfOrder(self, elementOrder):
2410 return self.mesh.NbTetrasOfOrder(elementOrder)
2412 ## Return the number of hexahedrons in the mesh
2413 # @return an integer value
2414 # @ingroup l1_meshinfo
2416 return self.mesh.NbHexas()
2418 ## Return the number of hexahedrons with the given order in the mesh
2419 # @param elementOrder the order of elements:
2420 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2421 # @return an integer value
2422 # @ingroup l1_meshinfo
2423 def NbHexasOfOrder(self, elementOrder):
2424 return self.mesh.NbHexasOfOrder(elementOrder)
2426 ## Return the number of triquadratic hexahedrons in the mesh
2427 # @return an integer value
2428 # @ingroup l1_meshinfo
2429 def NbTriQuadraticHexas(self):
2430 return self.mesh.NbTriQuadraticHexas()
2432 ## Return the number of pyramids in the mesh
2433 # @return an integer value
2434 # @ingroup l1_meshinfo
2435 def NbPyramids(self):
2436 return self.mesh.NbPyramids()
2438 ## Return the number of pyramids with the given order in the mesh
2439 # @param elementOrder the order of elements:
2440 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2441 # @return an integer value
2442 # @ingroup l1_meshinfo
2443 def NbPyramidsOfOrder(self, elementOrder):
2444 return self.mesh.NbPyramidsOfOrder(elementOrder)
2446 ## Return the number of prisms in the mesh
2447 # @return an integer value
2448 # @ingroup l1_meshinfo
2450 return self.mesh.NbPrisms()
2452 ## Return the number of prisms with the given order in the mesh
2453 # @param elementOrder the order of elements:
2454 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2455 # @return an integer value
2456 # @ingroup l1_meshinfo
2457 def NbPrismsOfOrder(self, elementOrder):
2458 return self.mesh.NbPrismsOfOrder(elementOrder)
2460 ## Return the number of hexagonal prisms in the mesh
2461 # @return an integer value
2462 # @ingroup l1_meshinfo
2463 def NbHexagonalPrisms(self):
2464 return self.mesh.NbHexagonalPrisms()
2466 ## Return the number of polyhedrons in the mesh
2467 # @return an integer value
2468 # @ingroup l1_meshinfo
2469 def NbPolyhedrons(self):
2470 return self.mesh.NbPolyhedrons()
2472 ## Return the number of submeshes in the mesh
2473 # @return an integer value
2474 # @ingroup l1_meshinfo
2475 def NbSubMesh(self):
2476 return self.mesh.NbSubMesh()
2478 ## Return the list of mesh elements IDs
2479 # @return the list of integer values
2480 # @ingroup l1_meshinfo
2481 def GetElementsId(self):
2482 return self.mesh.GetElementsId()
2484 ## Return the list of IDs of mesh elements with the given type
2485 # @param elementType the required type of elements, either of
2486 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2487 # @return list of integer values
2488 # @ingroup l1_meshinfo
2489 def GetElementsByType(self, elementType):
2490 return self.mesh.GetElementsByType(elementType)
2492 ## Return the list of mesh nodes IDs
2493 # @return the list of integer values
2494 # @ingroup l1_meshinfo
2495 def GetNodesId(self):
2496 return self.mesh.GetNodesId()
2498 # Get the information about mesh elements:
2499 # ------------------------------------
2501 ## Return the type of mesh element
2502 # @return the value from SMESH::ElementType enumeration
2503 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2504 # @ingroup l1_meshinfo
2505 def GetElementType(self, id, iselem=True):
2506 return self.mesh.GetElementType(id, iselem)
2508 ## Return the geometric type of mesh element
2509 # @return the value from SMESH::EntityType enumeration
2510 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2511 # @ingroup l1_meshinfo
2512 def GetElementGeomType(self, id):
2513 return self.mesh.GetElementGeomType(id)
2515 ## Return the shape type of mesh element
2516 # @return the value from SMESH::GeometryType enumeration.
2517 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2518 # @ingroup l1_meshinfo
2519 def GetElementShape(self, id):
2520 return self.mesh.GetElementShape(id)
2522 ## Return the list of submesh elements IDs
2523 # @param Shape a geom object(sub-shape)
2524 # Shape must be the sub-shape of a ShapeToMesh()
2525 # @return the list of integer values
2526 # @ingroup l1_meshinfo
2527 def GetSubMeshElementsId(self, Shape):
2528 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2529 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2532 return self.mesh.GetSubMeshElementsId(ShapeID)
2534 ## Return the list of submesh nodes IDs
2535 # @param Shape a geom object(sub-shape)
2536 # Shape must be the sub-shape of a ShapeToMesh()
2537 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2538 # @return the list of integer values
2539 # @ingroup l1_meshinfo
2540 def GetSubMeshNodesId(self, Shape, all):
2541 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2542 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2545 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2547 ## Return type of elements on given shape
2548 # @param Shape a geom object(sub-shape)
2549 # Shape must be a sub-shape of a ShapeToMesh()
2550 # @return element type
2551 # @ingroup l1_meshinfo
2552 def GetSubMeshElementType(self, Shape):
2553 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2554 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2557 return self.mesh.GetSubMeshElementType(ShapeID)
2559 ## Get the mesh description
2560 # @return string value
2561 # @ingroup l1_meshinfo
2563 return self.mesh.Dump()
2566 # Get the information about nodes and elements of a mesh by its IDs:
2567 # -----------------------------------------------------------
2569 ## Get XYZ coordinates of a node
2570 # \n If there is no nodes for the given ID - return an empty list
2571 # @return a list of double precision values
2572 # @ingroup l1_meshinfo
2573 def GetNodeXYZ(self, id):
2574 return self.mesh.GetNodeXYZ(id)
2576 ## Return list of IDs of inverse elements for the given node
2577 # \n If there is no node for the given ID - return an empty list
2578 # @return a list of integer values
2579 # @ingroup l1_meshinfo
2580 def GetNodeInverseElements(self, id):
2581 return self.mesh.GetNodeInverseElements(id)
2583 ## Return the position of a node on the shape
2584 # @return SMESH::NodePosition
2585 # @ingroup l1_meshinfo
2586 def GetNodePosition(self,NodeID):
2587 return self.mesh.GetNodePosition(NodeID)
2589 ## Return the position of an element on the shape
2590 # @return SMESH::ElementPosition
2591 # @ingroup l1_meshinfo
2592 def GetElementPosition(self,ElemID):
2593 return self.mesh.GetElementPosition(ElemID)
2595 ## Return the ID of the shape, on which the given node was generated.
2596 # @return an integer value > 0 or -1 if there is no node for the given
2597 # ID or the node is not assigned to any geometry
2598 # @ingroup l1_meshinfo
2599 def GetShapeID(self, id):
2600 return self.mesh.GetShapeID(id)
2602 ## Return the ID of the shape, on which the given element was generated.
2603 # @return an integer value > 0 or -1 if there is no element for the given
2604 # ID or the element is not assigned to any geometry
2605 # @ingroup l1_meshinfo
2606 def GetShapeIDForElem(self,id):
2607 return self.mesh.GetShapeIDForElem(id)
2609 ## Return the number of nodes of the given element
2610 # @return an integer value > 0 or -1 if there is no element for the given ID
2611 # @ingroup l1_meshinfo
2612 def GetElemNbNodes(self, id):
2613 return self.mesh.GetElemNbNodes(id)
2615 ## Return the node ID the given (zero based) index for the given element
2616 # \n If there is no element for the given ID - return -1
2617 # \n If there is no node for the given index - return -2
2618 # @return an integer value
2619 # @ingroup l1_meshinfo
2620 def GetElemNode(self, id, index):
2621 return self.mesh.GetElemNode(id, index)
2623 ## Return the IDs of nodes of the given element
2624 # @return a list of integer values
2625 # @ingroup l1_meshinfo
2626 def GetElemNodes(self, id):
2627 return self.mesh.GetElemNodes(id)
2629 ## Return true if the given node is the medium node in the given quadratic element
2630 # @ingroup l1_meshinfo
2631 def IsMediumNode(self, elementID, nodeID):
2632 return self.mesh.IsMediumNode(elementID, nodeID)
2634 ## Return true if the given node is the medium node in one of quadratic elements
2635 # @param nodeID ID of the node
2636 # @param elementType the type of elements to check a state of the node, either of
2637 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2638 # @ingroup l1_meshinfo
2639 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2640 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2642 ## Return the number of edges for the given element
2643 # @ingroup l1_meshinfo
2644 def ElemNbEdges(self, id):
2645 return self.mesh.ElemNbEdges(id)
2647 ## Return the number of faces for the given element
2648 # @ingroup l1_meshinfo
2649 def ElemNbFaces(self, id):
2650 return self.mesh.ElemNbFaces(id)
2652 ## Return nodes of given face (counted from zero) for given volumic element.
2653 # @ingroup l1_meshinfo
2654 def GetElemFaceNodes(self,elemId, faceIndex):
2655 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2657 ## Return three components of normal of given mesh face
2658 # (or an empty array in KO case)
2659 # @ingroup l1_meshinfo
2660 def GetFaceNormal(self, faceId, normalized=False):
2661 return self.mesh.GetFaceNormal(faceId,normalized)
2663 ## Return an element based on all given nodes.
2664 # @ingroup l1_meshinfo
2665 def FindElementByNodes(self, nodes):
2666 return self.mesh.FindElementByNodes(nodes)
2668 ## Return elements including all given nodes.
2669 # @ingroup l1_meshinfo
2670 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
2671 return self.mesh.GetElementsByNodes( nodes, elemType )
2673 ## Return true if the given element is a polygon
2674 # @ingroup l1_meshinfo
2675 def IsPoly(self, id):
2676 return self.mesh.IsPoly(id)
2678 ## Return true if the given element is quadratic
2679 # @ingroup l1_meshinfo
2680 def IsQuadratic(self, id):
2681 return self.mesh.IsQuadratic(id)
2683 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2684 # @ingroup l1_meshinfo
2685 def GetBallDiameter(self, id):
2686 return self.mesh.GetBallDiameter(id)
2688 ## Return XYZ coordinates of the barycenter of the given element
2689 # \n If there is no element for the given ID - return an empty list
2690 # @return a list of three double values
2691 # @ingroup l1_meshinfo
2692 def BaryCenter(self, id):
2693 return self.mesh.BaryCenter(id)
2695 ## Pass mesh elements through the given filter and return IDs of fitting elements
2696 # @param theFilter SMESH_Filter
2697 # @return a list of ids
2698 # @ingroup l1_controls
2699 def GetIdsFromFilter(self, theFilter):
2700 theFilter.SetMesh( self.mesh )
2701 return theFilter.GetIDs()
2703 # Get mesh measurements information:
2704 # ------------------------------------
2706 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2707 # Return a list of special structures (borders).
2708 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2709 # @ingroup l1_measurements
2710 def GetFreeBorders(self):
2711 aFilterMgr = self.smeshpyD.CreateFilterManager()
2712 aPredicate = aFilterMgr.CreateFreeEdges()
2713 aPredicate.SetMesh(self.mesh)
2714 aBorders = aPredicate.GetBorders()
2715 aFilterMgr.UnRegister()
2718 ## Get minimum distance between two nodes, elements or distance to the origin
2719 # @param id1 first node/element id
2720 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2721 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2722 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2723 # @return minimum distance value
2724 # @sa GetMinDistance()
2725 # @ingroup l1_measurements
2726 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2727 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2728 return aMeasure.value
2730 ## Get measure structure specifying minimum distance data between two objects
2731 # @param id1 first node/element id
2732 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2733 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2734 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2735 # @return Measure structure
2737 # @ingroup l1_measurements
2738 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2740 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2742 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2745 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2747 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2752 aMeasurements = self.smeshpyD.CreateMeasurements()
2753 aMeasure = aMeasurements.MinDistance(id1, id2)
2754 genObjUnRegister([aMeasurements,id1, id2])
2757 ## Get bounding box of the specified object(s)
2758 # @param objects single source object or list of source objects or list of nodes/elements IDs
2759 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2760 # @c False specifies that @a objects are nodes
2761 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2762 # @sa GetBoundingBox()
2763 # @ingroup l1_measurements
2764 def BoundingBox(self, objects=None, isElem=False):
2765 result = self.GetBoundingBox(objects, isElem)
2769 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2772 ## Get measure structure specifying bounding box data of the specified object(s)
2773 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2774 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2775 # @c False specifies that @a objects are nodes
2776 # @return Measure structure
2778 # @ingroup l1_measurements
2779 def GetBoundingBox(self, IDs=None, isElem=False):
2782 elif isinstance(IDs, tuple):
2784 if not isinstance(IDs, list):
2786 if len(IDs) > 0 and isinstance(IDs[0], int):
2789 unRegister = genObjUnRegister()
2791 if isinstance(o, Mesh):
2792 srclist.append(o.mesh)
2793 elif hasattr(o, "_narrow"):
2794 src = o._narrow(SMESH.SMESH_IDSource)
2795 if src: srclist.append(src)
2797 elif isinstance(o, list):
2799 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2801 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2802 unRegister.set( srclist[-1] )
2805 aMeasurements = self.smeshpyD.CreateMeasurements()
2806 unRegister.set( aMeasurements )
2807 aMeasure = aMeasurements.BoundingBox(srclist)
2810 # Mesh edition (SMESH_MeshEditor functionality):
2811 # ---------------------------------------------
2813 ## Remove the elements from the mesh by ids
2814 # @param IDsOfElements is a list of ids of elements to remove
2815 # @return True or False
2816 # @ingroup l2_modif_del
2817 def RemoveElements(self, IDsOfElements):
2818 return self.editor.RemoveElements(IDsOfElements)
2820 ## Remove nodes from mesh by ids
2821 # @param IDsOfNodes is a list of ids of nodes to remove
2822 # @return True or False
2823 # @ingroup l2_modif_del
2824 def RemoveNodes(self, IDsOfNodes):
2825 return self.editor.RemoveNodes(IDsOfNodes)
2827 ## Remove all orphan (free) nodes from mesh
2828 # @return number of the removed nodes
2829 # @ingroup l2_modif_del
2830 def RemoveOrphanNodes(self):
2831 return self.editor.RemoveOrphanNodes()
2833 ## Add a node to the mesh by coordinates
2834 # @return Id of the new node
2835 # @ingroup l2_modif_add
2836 def AddNode(self, x, y, z):
2837 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2838 if hasVars: self.mesh.SetParameters(Parameters)
2839 return self.editor.AddNode( x, y, z)
2841 ## Create a 0D element on a node with given number.
2842 # @param IDOfNode the ID of node for creation of the element.
2843 # @param DuplicateElements to add one more 0D element to a node or not
2844 # @return the Id of the new 0D element
2845 # @ingroup l2_modif_add
2846 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2847 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2849 ## Create 0D elements on all nodes of the given elements except those
2850 # nodes on which a 0D element already exists.
2851 # @param theObject an object on whose nodes 0D elements will be created.
2852 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2853 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2854 # @param theGroupName optional name of a group to add 0D elements created
2855 # and/or found on nodes of \a theObject.
2856 # @param DuplicateElements to add one more 0D element to a node or not
2857 # @return an object (a new group or a temporary SMESH_IDSource) holding
2858 # IDs of new and/or found 0D elements. IDs of 0D elements
2859 # can be retrieved from the returned object by calling GetIDs()
2860 # @ingroup l2_modif_add
2861 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2862 unRegister = genObjUnRegister()
2863 if isinstance( theObject, Mesh ):
2864 theObject = theObject.GetMesh()
2865 elif isinstance( theObject, list ):
2866 theObject = self.GetIDSource( theObject, SMESH.ALL )
2867 unRegister.set( theObject )
2868 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2870 ## Create a ball element on a node with given ID.
2871 # @param IDOfNode the ID of node for creation of the element.
2872 # @param diameter the bal diameter.
2873 # @return the Id of the new ball element
2874 # @ingroup l2_modif_add
2875 def AddBall(self, IDOfNode, diameter):
2876 return self.editor.AddBall( IDOfNode, diameter )
2878 ## Create a linear or quadratic edge (this is determined
2879 # by the number of given nodes).
2880 # @param IDsOfNodes the list of node IDs for creation of the element.
2881 # The order of nodes in this list should correspond to the description
2882 # of MED. \n This description is located by the following link:
2883 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2884 # @return the Id of the new edge
2885 # @ingroup l2_modif_add
2886 def AddEdge(self, IDsOfNodes):
2887 return self.editor.AddEdge(IDsOfNodes)
2889 ## Create a linear or quadratic face (this is determined
2890 # by the number of given nodes).
2891 # @param IDsOfNodes the list of node IDs for creation of the element.
2892 # The order of nodes in this list should correspond to the description
2893 # of MED. \n This description is located by the following link:
2894 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2895 # @return the Id of the new face
2896 # @ingroup l2_modif_add
2897 def AddFace(self, IDsOfNodes):
2898 return self.editor.AddFace(IDsOfNodes)
2900 ## Add a polygonal face to the mesh by the list of node IDs
2901 # @param IdsOfNodes the list of node IDs for creation of the element.
2902 # @return the Id of the new face
2903 # @ingroup l2_modif_add
2904 def AddPolygonalFace(self, IdsOfNodes):
2905 return self.editor.AddPolygonalFace(IdsOfNodes)
2907 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2908 # @param IdsOfNodes the list of node IDs for creation of the element;
2909 # corner nodes follow first.
2910 # @return the Id of the new face
2911 # @ingroup l2_modif_add
2912 def AddQuadPolygonalFace(self, IdsOfNodes):
2913 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2915 ## Create both simple and quadratic volume (this is determined
2916 # by the number of given nodes).
2917 # @param IDsOfNodes the list of node IDs for creation of the element.
2918 # The order of nodes in this list should correspond to the description
2919 # of MED. \n This description is located by the following link:
2920 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2921 # @return the Id of the new volumic element
2922 # @ingroup l2_modif_add
2923 def AddVolume(self, IDsOfNodes):
2924 return self.editor.AddVolume(IDsOfNodes)
2926 ## Create a volume of many faces, giving nodes for each face.
2927 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2928 # @param Quantities the list of integer values, Quantities[i]
2929 # gives the quantity of nodes in face number i.
2930 # @return the Id of the new volumic element
2931 # @ingroup l2_modif_add
2932 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2933 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2935 ## Create a volume of many faces, giving the IDs of the existing faces.
2936 # @param IdsOfFaces the list of face IDs for volume creation.
2938 # Note: The created volume will refer only to the nodes
2939 # of the given faces, not to the faces themselves.
2940 # @return the Id of the new volumic element
2941 # @ingroup l2_modif_add
2942 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2943 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2946 ## @brief Binds a node to a vertex
2947 # @param NodeID a node ID
2948 # @param Vertex a vertex or vertex ID
2949 # @return True if succeed else raises an exception
2950 # @ingroup l2_modif_add
2951 def SetNodeOnVertex(self, NodeID, Vertex):
2952 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2953 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2957 self.editor.SetNodeOnVertex(NodeID, VertexID)
2958 except SALOME.SALOME_Exception, inst:
2959 raise ValueError, inst.details.text
2963 ## @brief Stores the node position on an edge
2964 # @param NodeID a node ID
2965 # @param Edge an edge or edge ID
2966 # @param paramOnEdge a parameter on the edge where the node is located
2967 # @return True if succeed else raises an exception
2968 # @ingroup l2_modif_add
2969 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2970 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2971 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2975 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2976 except SALOME.SALOME_Exception, inst:
2977 raise ValueError, inst.details.text
2980 ## @brief Stores node position on a face
2981 # @param NodeID a node ID
2982 # @param Face a face or face ID
2983 # @param u U parameter on the face where the node is located
2984 # @param v V parameter on the face where the node is located
2985 # @return True if succeed else raises an exception
2986 # @ingroup l2_modif_add
2987 def SetNodeOnFace(self, NodeID, Face, u, v):
2988 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2989 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2993 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2994 except SALOME.SALOME_Exception, inst:
2995 raise ValueError, inst.details.text
2998 ## @brief Binds a node to a solid
2999 # @param NodeID a node ID
3000 # @param Solid a solid or solid ID
3001 # @return True if succeed else raises an exception
3002 # @ingroup l2_modif_add
3003 def SetNodeInVolume(self, NodeID, Solid):
3004 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3005 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3009 self.editor.SetNodeInVolume(NodeID, SolidID)
3010 except SALOME.SALOME_Exception, inst:
3011 raise ValueError, inst.details.text
3014 ## @brief Bind an element to a shape
3015 # @param ElementID an element ID
3016 # @param Shape a shape or shape ID
3017 # @return True if succeed else raises an exception
3018 # @ingroup l2_modif_add
3019 def SetMeshElementOnShape(self, ElementID, Shape):
3020 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3021 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3025 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3026 except SALOME.SALOME_Exception, inst:
3027 raise ValueError, inst.details.text
3031 ## Move the node with the given id
3032 # @param NodeID the id of the node
3033 # @param x a new X coordinate
3034 # @param y a new Y coordinate
3035 # @param z a new Z coordinate
3036 # @return True if succeed else False
3037 # @ingroup l2_modif_edit
3038 def MoveNode(self, NodeID, x, y, z):
3039 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3040 if hasVars: self.mesh.SetParameters(Parameters)
3041 return self.editor.MoveNode(NodeID, x, y, z)
3043 ## Find the node closest to a point and moves it to a point location
3044 # @param x the X coordinate of a point
3045 # @param y the Y coordinate of a point
3046 # @param z the Z coordinate of a point
3047 # @param NodeID if specified (>0), the node with this ID is moved,
3048 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3049 # @return the ID of a node
3050 # @ingroup l2_modif_edit
3051 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3052 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3053 if hasVars: self.mesh.SetParameters(Parameters)
3054 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3056 ## Find the node closest to a point
3057 # @param x the X coordinate of a point
3058 # @param y the Y coordinate of a point
3059 # @param z the Z coordinate of a point
3060 # @return the ID of a node
3061 # @ingroup l1_meshinfo
3062 def FindNodeClosestTo(self, x, y, z):
3063 #preview = self.mesh.GetMeshEditPreviewer()
3064 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3065 return self.editor.FindNodeClosestTo(x, y, z)
3067 ## Find the elements where a point lays IN or ON
3068 # @param x the X coordinate of a point
3069 # @param y the Y coordinate of a point
3070 # @param z the Z coordinate of a point
3071 # @param elementType type of elements to find; either of
3072 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3073 # means elements of any type excluding nodes, discrete and 0D elements.
3074 # @param meshPart a part of mesh (group, sub-mesh) to search within
3075 # @return list of IDs of found elements
3076 # @ingroup l1_meshinfo
3077 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3079 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3081 return self.editor.FindElementsByPoint(x, y, z, elementType)
3083 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3084 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3085 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3086 # @ingroup l1_meshinfo
3087 def GetPointState(self, x, y, z):
3088 return self.editor.GetPointState(x, y, z)
3090 ## Find the node closest to a point and moves it to a point location
3091 # @param x the X coordinate of a point
3092 # @param y the Y coordinate of a point
3093 # @param z the Z coordinate of a point
3094 # @return the ID of a moved node
3095 # @ingroup l2_modif_edit
3096 def MeshToPassThroughAPoint(self, x, y, z):
3097 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3099 ## Replace two neighbour triangles sharing Node1-Node2 link
3100 # with the triangles built on the same 4 nodes but having other common link.
3101 # @param NodeID1 the ID of the first node
3102 # @param NodeID2 the ID of the second node
3103 # @return false if proper faces were not found
3104 # @ingroup l2_modif_cutquadr
3105 def InverseDiag(self, NodeID1, NodeID2):
3106 return self.editor.InverseDiag(NodeID1, NodeID2)
3108 ## Replace two neighbour triangles sharing Node1-Node2 link
3109 # with a quadrangle built on the same 4 nodes.
3110 # @param NodeID1 the ID of the first node
3111 # @param NodeID2 the ID of the second node
3112 # @return false if proper faces were not found
3113 # @ingroup l2_modif_unitetri
3114 def DeleteDiag(self, NodeID1, NodeID2):
3115 return self.editor.DeleteDiag(NodeID1, NodeID2)
3117 ## Reorient elements by ids
3118 # @param IDsOfElements if undefined reorients all mesh elements
3119 # @return True if succeed else False
3120 # @ingroup l2_modif_changori
3121 def Reorient(self, IDsOfElements=None):
3122 if IDsOfElements == None:
3123 IDsOfElements = self.GetElementsId()
3124 return self.editor.Reorient(IDsOfElements)
3126 ## Reorient all elements of the object
3127 # @param theObject mesh, submesh or group
3128 # @return True if succeed else False
3129 # @ingroup l2_modif_changori
3130 def ReorientObject(self, theObject):
3131 if ( isinstance( theObject, Mesh )):
3132 theObject = theObject.GetMesh()
3133 return self.editor.ReorientObject(theObject)
3135 ## Reorient faces contained in \a the2DObject.
3136 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3137 # @param theDirection is a desired direction of normal of \a theFace.
3138 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3139 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3140 # compared with theDirection. It can be either ID of face or a point
3141 # by which the face will be found. The point can be given as either
3142 # a GEOM vertex or a list of point coordinates.
3143 # @return number of reoriented faces
3144 # @ingroup l2_modif_changori
3145 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3146 unRegister = genObjUnRegister()
3148 if isinstance( the2DObject, Mesh ):
3149 the2DObject = the2DObject.GetMesh()
3150 if isinstance( the2DObject, list ):
3151 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3152 unRegister.set( the2DObject )
3153 # check theDirection
3154 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3155 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3156 if isinstance( theDirection, list ):
3157 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3158 # prepare theFace and thePoint
3159 theFace = theFaceOrPoint
3160 thePoint = PointStruct(0,0,0)
3161 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3162 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3164 if isinstance( theFaceOrPoint, list ):
3165 thePoint = PointStruct( *theFaceOrPoint )
3167 if isinstance( theFaceOrPoint, PointStruct ):
3168 thePoint = theFaceOrPoint
3170 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3172 ## Reorient faces according to adjacent volumes.
3173 # @param the2DObject is a mesh, sub-mesh, group or list of
3174 # either IDs of faces or face groups.
3175 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3176 # @param theOutsideNormal to orient faces to have their normals
3177 # pointing either \a outside or \a inside the adjacent volumes.
3178 # @return number of reoriented faces.
3179 # @ingroup l2_modif_changori
3180 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3181 unRegister = genObjUnRegister()
3183 if not isinstance( the2DObject, list ):
3184 the2DObject = [ the2DObject ]
3185 elif the2DObject and isinstance( the2DObject[0], int ):
3186 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3187 unRegister.set( the2DObject )
3188 the2DObject = [ the2DObject ]
3189 for i,obj2D in enumerate( the2DObject ):
3190 if isinstance( obj2D, Mesh ):
3191 the2DObject[i] = obj2D.GetMesh()
3192 if isinstance( obj2D, list ):
3193 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3194 unRegister.set( the2DObject[i] )
3196 if isinstance( the3DObject, Mesh ):
3197 the3DObject = the3DObject.GetMesh()
3198 if isinstance( the3DObject, list ):
3199 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3200 unRegister.set( the3DObject )
3201 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3203 ## Fuse the neighbouring triangles into quadrangles.
3204 # @param IDsOfElements The triangles to be fused.
3205 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3206 # applied to possible quadrangles to choose a neighbour to fuse with.
3207 # Type SMESH.FunctorType._items in the Python Console to see all items.
3208 # Note that not all items correspond to numerical functors.
3209 # @param MaxAngle is the maximum angle between element normals at which the fusion
3210 # is still performed; theMaxAngle is mesured in radians.
3211 # Also it could be a name of variable which defines angle in degrees.
3212 # @return TRUE in case of success, FALSE otherwise.
3213 # @ingroup l2_modif_unitetri
3214 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3215 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3216 self.mesh.SetParameters(Parameters)
3217 if not IDsOfElements:
3218 IDsOfElements = self.GetElementsId()
3219 Functor = self.smeshpyD.GetFunctor(theCriterion)
3220 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3222 ## Fuse the neighbouring triangles of the object into quadrangles
3223 # @param theObject is mesh, submesh or group
3224 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3225 # applied to possible quadrangles to choose a neighbour to fuse with.
3226 # Type SMESH.FunctorType._items in the Python Console to see all items.
3227 # Note that not all items correspond to numerical functors.
3228 # @param MaxAngle a max angle between element normals at which the fusion
3229 # is still performed; theMaxAngle is mesured in radians.
3230 # @return TRUE in case of success, FALSE otherwise.
3231 # @ingroup l2_modif_unitetri
3232 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3233 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3234 self.mesh.SetParameters(Parameters)
3235 if isinstance( theObject, Mesh ):
3236 theObject = theObject.GetMesh()
3237 Functor = self.smeshpyD.GetFunctor(theCriterion)
3238 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3240 ## Split quadrangles into triangles.
3241 # @param IDsOfElements the faces to be splitted.
3242 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3243 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3244 # value, then quadrangles will be split by the smallest diagonal.
3245 # Type SMESH.FunctorType._items in the Python Console to see all items.
3246 # Note that not all items correspond to numerical functors.
3247 # @return TRUE in case of success, FALSE otherwise.
3248 # @ingroup l2_modif_cutquadr
3249 def QuadToTri (self, IDsOfElements, theCriterion = None):
3250 if IDsOfElements == []:
3251 IDsOfElements = self.GetElementsId()
3252 if theCriterion is None:
3253 theCriterion = FT_MaxElementLength2D
3254 Functor = self.smeshpyD.GetFunctor(theCriterion)
3255 return self.editor.QuadToTri(IDsOfElements, Functor)
3257 ## Split quadrangles into triangles.
3258 # @param theObject the object from which the list of elements is taken,
3259 # this is mesh, submesh or group
3260 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3261 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3262 # value, then quadrangles will be split by the smallest diagonal.
3263 # Type SMESH.FunctorType._items in the Python Console to see all items.
3264 # Note that not all items correspond to numerical functors.
3265 # @return TRUE in case of success, FALSE otherwise.
3266 # @ingroup l2_modif_cutquadr
3267 def QuadToTriObject (self, theObject, theCriterion = None):
3268 if ( isinstance( theObject, Mesh )):
3269 theObject = theObject.GetMesh()
3270 if theCriterion is None:
3271 theCriterion = FT_MaxElementLength2D
3272 Functor = self.smeshpyD.GetFunctor(theCriterion)
3273 return self.editor.QuadToTriObject(theObject, Functor)
3275 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3277 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3278 # group or a list of face IDs. By default all quadrangles are split
3279 # @ingroup l2_modif_cutquadr
3280 def QuadTo4Tri (self, theElements=[]):
3281 unRegister = genObjUnRegister()
3282 if isinstance( theElements, Mesh ):
3283 theElements = theElements.mesh
3284 elif not theElements:
3285 theElements = self.mesh
3286 elif isinstance( theElements, list ):
3287 theElements = self.GetIDSource( theElements, SMESH.FACE )
3288 unRegister.set( theElements )
3289 return self.editor.QuadTo4Tri( theElements )
3291 ## Split quadrangles into triangles.
3292 # @param IDsOfElements the faces to be splitted
3293 # @param Diag13 is used to choose a diagonal for splitting.
3294 # @return TRUE in case of success, FALSE otherwise.
3295 # @ingroup l2_modif_cutquadr
3296 def SplitQuad (self, IDsOfElements, Diag13):
3297 if IDsOfElements == []:
3298 IDsOfElements = self.GetElementsId()
3299 return self.editor.SplitQuad(IDsOfElements, Diag13)
3301 ## Split quadrangles into triangles.
3302 # @param theObject the object from which the list of elements is taken,
3303 # this is mesh, submesh or group
3304 # @param Diag13 is used to choose a diagonal for splitting.
3305 # @return TRUE in case of success, FALSE otherwise.
3306 # @ingroup l2_modif_cutquadr
3307 def SplitQuadObject (self, theObject, Diag13):
3308 if ( isinstance( theObject, Mesh )):
3309 theObject = theObject.GetMesh()
3310 return self.editor.SplitQuadObject(theObject, Diag13)
3312 ## Find a better splitting of the given quadrangle.
3313 # @param IDOfQuad the ID of the quadrangle to be splitted.
3314 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3315 # choose a diagonal for splitting.
3316 # Type SMESH.FunctorType._items in the Python Console to see all items.
3317 # Note that not all items correspond to numerical functors.
3318 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3319 # diagonal is better, 0 if error occurs.
3320 # @ingroup l2_modif_cutquadr
3321 def BestSplit (self, IDOfQuad, theCriterion):
3322 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3324 ## Split volumic elements into tetrahedrons
3325 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3326 # @param method flags passing splitting method:
3327 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3328 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3329 # @ingroup l2_modif_cutquadr
3330 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3331 unRegister = genObjUnRegister()
3332 if isinstance( elems, Mesh ):
3333 elems = elems.GetMesh()
3334 if ( isinstance( elems, list )):
3335 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3336 unRegister.set( elems )
3337 self.editor.SplitVolumesIntoTetra(elems, method)
3340 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3341 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3342 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3343 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3344 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3345 # will be split in order to keep the mesh conformal.
3346 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3347 # if None (default), all bi-quadratic elements will be split
3348 # @ingroup l2_modif_cutquadr
3349 def SplitBiQuadraticIntoLinear(self, elems=None):
3350 unRegister = genObjUnRegister()
3351 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3352 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3353 unRegister.set( elems )
3355 elems = [ self.GetMesh() ]
3356 if isinstance( elems, Mesh ):
3357 elems = [ elems.GetMesh() ]
3358 if not isinstance( elems, list ):
3360 self.editor.SplitBiQuadraticIntoLinear( elems )
3362 ## Split hexahedra into prisms
3363 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3364 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3365 # gives a normal vector defining facets to split into triangles.
3366 # @a startHexPoint can be either a triple of coordinates or a vertex.
3367 # @param facetNormal a normal to a facet to split into triangles of a
3368 # hexahedron found by @a startHexPoint.
3369 # @a facetNormal can be either a triple of coordinates or an edge.
3370 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3371 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3372 # @param allDomains if @c False, only hexahedra adjacent to one closest
3373 # to @a startHexPoint are split, else @a startHexPoint
3374 # is used to find the facet to split in all domains present in @a elems.
3375 # @ingroup l2_modif_cutquadr
3376 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3377 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3379 unRegister = genObjUnRegister()
3380 if isinstance( elems, Mesh ):
3381 elems = elems.GetMesh()
3382 if ( isinstance( elems, list )):
3383 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3384 unRegister.set( elems )
3387 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3388 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3389 elif isinstance( startHexPoint, list ):
3390 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3393 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3394 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3395 elif isinstance( facetNormal, list ):
3396 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3399 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3401 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3403 ## Split quadrangle faces near triangular facets of volumes
3405 # @ingroup l2_modif_cutquadr
3406 def SplitQuadsNearTriangularFacets(self):
3407 faces_array = self.GetElementsByType(SMESH.FACE)
3408 for face_id in faces_array:
3409 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3410 quad_nodes = self.mesh.GetElemNodes(face_id)
3411 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3412 isVolumeFound = False
3413 for node1_elem in node1_elems:
3414 if not isVolumeFound:
3415 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3416 nb_nodes = self.GetElemNbNodes(node1_elem)
3417 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3418 volume_elem = node1_elem
3419 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3420 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3421 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3422 isVolumeFound = True
3423 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3424 self.SplitQuad([face_id], False) # diagonal 2-4
3425 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3426 isVolumeFound = True
3427 self.SplitQuad([face_id], True) # diagonal 1-3
3428 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3429 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3430 isVolumeFound = True
3431 self.SplitQuad([face_id], True) # diagonal 1-3
3433 ## @brief Splits hexahedrons into tetrahedrons.
3435 # This operation uses pattern mapping functionality for splitting.
3436 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3437 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3438 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3439 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3440 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3441 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3442 # @return TRUE in case of success, FALSE otherwise.
3443 # @ingroup l2_modif_cutquadr
3444 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3445 # Pattern: 5.---------.6
3450 # (0,0,1) 4.---------.7 * |
3457 # (0,0,0) 0.---------.3
3458 pattern_tetra = "!!! Nb of points: \n 8 \n\
3468 !!! Indices of points of 6 tetras: \n\
3476 pattern = self.smeshpyD.GetPattern()
3477 isDone = pattern.LoadFromFile(pattern_tetra)
3479 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3482 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3483 isDone = pattern.MakeMesh(self.mesh, False, False)
3484 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3486 # split quafrangle faces near triangular facets of volumes
3487 self.SplitQuadsNearTriangularFacets()
3491 ## @brief Split hexahedrons into prisms.
3493 # Uses the pattern mapping functionality for splitting.
3494 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3495 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3496 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3497 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3498 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3499 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3500 # @return TRUE in case of success, FALSE otherwise.
3501 # @ingroup l2_modif_cutquadr
3502 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3503 # Pattern: 5.---------.6
3508 # (0,0,1) 4.---------.7 |
3515 # (0,0,0) 0.---------.3
3516 pattern_prism = "!!! Nb of points: \n 8 \n\
3526 !!! Indices of points of 2 prisms: \n\
3530 pattern = self.smeshpyD.GetPattern()
3531 isDone = pattern.LoadFromFile(pattern_prism)
3533 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3536 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3537 isDone = pattern.MakeMesh(self.mesh, False, False)
3538 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3540 # Split quafrangle faces near triangular facets of volumes
3541 self.SplitQuadsNearTriangularFacets()
3546 # @param IDsOfElements the list if ids of elements to smooth
3547 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3548 # Note that nodes built on edges and boundary nodes are always fixed.
3549 # @param MaxNbOfIterations the maximum number of iterations
3550 # @param MaxAspectRatio varies in range [1.0, inf]
3551 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3552 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3553 # @return TRUE in case of success, FALSE otherwise.
3554 # @ingroup l2_modif_smooth
3555 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3556 MaxNbOfIterations, MaxAspectRatio, Method):
3557 if IDsOfElements == []:
3558 IDsOfElements = self.GetElementsId()
3559 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3560 self.mesh.SetParameters(Parameters)
3561 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3562 MaxNbOfIterations, MaxAspectRatio, Method)
3564 ## Smooth elements which belong to the given object
3565 # @param theObject the object to smooth
3566 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3567 # Note that nodes built on edges and boundary nodes are always fixed.
3568 # @param MaxNbOfIterations the maximum number of iterations
3569 # @param MaxAspectRatio varies in range [1.0, inf]
3570 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3571 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3572 # @return TRUE in case of success, FALSE otherwise.
3573 # @ingroup l2_modif_smooth
3574 def SmoothObject(self, theObject, IDsOfFixedNodes,
3575 MaxNbOfIterations, MaxAspectRatio, Method):
3576 if ( isinstance( theObject, Mesh )):
3577 theObject = theObject.GetMesh()
3578 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3579 MaxNbOfIterations, MaxAspectRatio, Method)
3581 ## Parametrically smooth the given elements
3582 # @param IDsOfElements the list if ids of elements to smooth
3583 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3584 # Note that nodes built on edges and boundary nodes are always fixed.
3585 # @param MaxNbOfIterations the maximum number of iterations
3586 # @param MaxAspectRatio varies in range [1.0, inf]
3587 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3588 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3589 # @return TRUE in case of success, FALSE otherwise.
3590 # @ingroup l2_modif_smooth
3591 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3592 MaxNbOfIterations, MaxAspectRatio, Method):
3593 if IDsOfElements == []:
3594 IDsOfElements = self.GetElementsId()
3595 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3596 self.mesh.SetParameters(Parameters)
3597 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3598 MaxNbOfIterations, MaxAspectRatio, Method)
3600 ## Parametrically smooth the elements which belong to the given object
3601 # @param theObject the object to smooth
3602 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3603 # Note that nodes built on edges and boundary nodes are always fixed.
3604 # @param MaxNbOfIterations the maximum number of iterations
3605 # @param MaxAspectRatio varies in range [1.0, inf]
3606 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3607 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3608 # @return TRUE in case of success, FALSE otherwise.
3609 # @ingroup l2_modif_smooth
3610 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3611 MaxNbOfIterations, MaxAspectRatio, Method):
3612 if ( isinstance( theObject, Mesh )):
3613 theObject = theObject.GetMesh()
3614 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3615 MaxNbOfIterations, MaxAspectRatio, Method)
3617 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3618 # them with quadratic with the same id.
3619 # @param theForce3d new node creation method:
3620 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3621 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3622 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3623 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3624 # @return SMESH.ComputeError which can hold a warning
3625 # @ingroup l2_modif_tofromqu
3626 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3627 if isinstance( theSubMesh, Mesh ):
3628 theSubMesh = theSubMesh.mesh
3630 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3633 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3635 self.editor.ConvertToQuadratic(theForce3d)
3636 error = self.editor.GetLastError()
3637 if error and error.comment:
3641 ## Convert the mesh from quadratic to ordinary,
3642 # deletes old quadratic elements, \n replacing
3643 # them with ordinary mesh elements with the same id.
3644 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3645 # @ingroup l2_modif_tofromqu
3646 def ConvertFromQuadratic(self, theSubMesh=None):
3648 self.editor.ConvertFromQuadraticObject(theSubMesh)
3650 return self.editor.ConvertFromQuadratic()
3652 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3653 # @return TRUE if operation has been completed successfully, FALSE otherwise
3654 # @ingroup l2_modif_add
3655 def Make2DMeshFrom3D(self):
3656 return self.editor.Make2DMeshFrom3D()
3658 ## Create missing boundary elements
3659 # @param elements - elements whose boundary is to be checked:
3660 # mesh, group, sub-mesh or list of elements
3661 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3662 # @param dimension - defines type of boundary elements to create, either of
3663 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3664 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3665 # @param groupName - a name of group to store created boundary elements in,
3666 # "" means not to create the group
3667 # @param meshName - a name of new mesh to store created boundary elements in,
3668 # "" means not to create the new mesh
3669 # @param toCopyElements - if true, the checked elements will be copied into
3670 # the new mesh else only boundary elements will be copied into the new mesh
3671 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3672 # boundary elements will be copied into the new mesh
3673 # @return tuple (mesh, group) where boundary elements were added to
3674 # @ingroup l2_modif_add
3675 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3676 toCopyElements=False, toCopyExistingBondary=False):
3677 unRegister = genObjUnRegister()
3678 if isinstance( elements, Mesh ):
3679 elements = elements.GetMesh()
3680 if ( isinstance( elements, list )):
3681 elemType = SMESH.ALL
3682 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3683 elements = self.editor.MakeIDSource(elements, elemType)
3684 unRegister.set( elements )
3685 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3686 toCopyElements,toCopyExistingBondary)
3687 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3691 # @brief Create missing boundary elements around either the whole mesh or
3692 # groups of elements
3693 # @param dimension - defines type of boundary elements to create, either of
3694 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3695 # @param groupName - a name of group to store all boundary elements in,
3696 # "" means not to create the group
3697 # @param meshName - a name of a new mesh, which is a copy of the initial
3698 # mesh + created boundary elements; "" means not to create the new mesh
3699 # @param toCopyAll - if true, the whole initial mesh will be copied into
3700 # the new mesh else only boundary elements will be copied into the new mesh
3701 # @param groups - groups of elements to make boundary around
3702 # @retval tuple( long, mesh, groups )
3703 # long - number of added boundary elements
3704 # mesh - the mesh where elements were added to
3705 # group - the group of boundary elements or None
3707 # @ingroup l2_modif_add
3708 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3709 toCopyAll=False, groups=[]):
3710 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3712 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3713 return nb, mesh, group
3715 ## Renumber mesh nodes (Obsolete, does nothing)
3716 # @ingroup l2_modif_renumber
3717 def RenumberNodes(self):
3718 self.editor.RenumberNodes()
3720 ## Renumber mesh elements (Obsole, does nothing)
3721 # @ingroup l2_modif_renumber
3722 def RenumberElements(self):
3723 self.editor.RenumberElements()
3725 ## Private method converting \a arg into a list of SMESH_IdSource's
3726 def _getIdSourceList(self, arg, idType, unRegister):
3727 if arg and isinstance( arg, list ):
3728 if isinstance( arg[0], int ):
3729 arg = self.GetIDSource( arg, idType )
3730 unRegister.set( arg )
3731 elif isinstance( arg[0], Mesh ):
3732 arg[0] = arg[0].GetMesh()
3733 elif isinstance( arg, Mesh ):
3735 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3739 ## Generate new elements by rotation of the given elements and nodes around the axis
3740 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3741 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3742 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3743 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3744 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3745 # which defines angle in degrees
3746 # @param NbOfSteps the number of steps
3747 # @param Tolerance tolerance
3748 # @param MakeGroups forces the generation of new groups from existing ones
3749 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3750 # of all steps, else - size of each step
3751 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3752 # @ingroup l2_modif_extrurev
3753 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3754 MakeGroups=False, TotalAngle=False):
3755 unRegister = genObjUnRegister()
3756 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3757 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3758 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3760 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3761 Axis = self.smeshpyD.GetAxisStruct( Axis )
3762 if isinstance( Axis, list ):
3763 Axis = SMESH.AxisStruct( *Axis )
3765 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3766 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3767 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3768 self.mesh.SetParameters(Parameters)
3769 if TotalAngle and NbOfSteps:
3770 AngleInRadians /= NbOfSteps
3771 return self.editor.RotationSweepObjects( nodes, edges, faces,
3772 Axis, AngleInRadians,
3773 NbOfSteps, Tolerance, MakeGroups)
3775 ## Generate new elements by rotation of the elements around the axis
3776 # @param IDsOfElements the list of ids of elements to sweep
3777 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3778 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3779 # @param NbOfSteps the number of steps
3780 # @param Tolerance tolerance
3781 # @param MakeGroups forces the generation of new groups from existing ones
3782 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3783 # of all steps, else - size of each step
3784 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3785 # @ingroup l2_modif_extrurev
3786 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3787 MakeGroups=False, TotalAngle=False):
3788 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3789 AngleInRadians, NbOfSteps, Tolerance,
3790 MakeGroups, TotalAngle)
3792 ## Generate new elements by rotation of the elements of object around the axis
3793 # @param theObject object which elements should be sweeped.
3794 # It can be a mesh, a sub mesh or a group.
3795 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3796 # @param AngleInRadians the angle of Rotation
3797 # @param NbOfSteps number of steps
3798 # @param Tolerance tolerance
3799 # @param MakeGroups forces the generation of new groups from existing ones
3800 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3801 # of all steps, else - size of each step
3802 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3803 # @ingroup l2_modif_extrurev
3804 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3805 MakeGroups=False, TotalAngle=False):
3806 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3807 AngleInRadians, NbOfSteps, Tolerance,
3808 MakeGroups, TotalAngle )
3810 ## Generate new elements by rotation of the elements of object around the axis
3811 # @param theObject object which elements should be sweeped.
3812 # It can be a mesh, a sub mesh or a group.
3813 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3814 # @param AngleInRadians the angle of Rotation
3815 # @param NbOfSteps number of steps
3816 # @param Tolerance tolerance
3817 # @param MakeGroups forces the generation of new groups from existing ones
3818 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3819 # of all steps, else - size of each step
3820 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3821 # @ingroup l2_modif_extrurev
3822 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3823 MakeGroups=False, TotalAngle=False):
3824 return self.RotationSweepObjects([],theObject,[], Axis,
3825 AngleInRadians, NbOfSteps, Tolerance,
3826 MakeGroups, TotalAngle)
3828 ## Generate new elements by rotation of the elements of object around the axis
3829 # @param theObject object which elements should be sweeped.
3830 # It can be a mesh, a sub mesh or a group.
3831 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3832 # @param AngleInRadians the angle of Rotation
3833 # @param NbOfSteps number of steps
3834 # @param Tolerance tolerance
3835 # @param MakeGroups forces the generation of new groups from existing ones
3836 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3837 # of all steps, else - size of each step
3838 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3839 # @ingroup l2_modif_extrurev
3840 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3841 MakeGroups=False, TotalAngle=False):
3842 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3843 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3845 ## Generate new elements by extrusion of the given elements and nodes
3846 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3847 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3848 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3849 # @param StepVector vector or DirStruct or 3 vector components, defining
3850 # the direction and value of extrusion for one step (the total extrusion
3851 # length will be NbOfSteps * ||StepVector||)
3852 # @param NbOfSteps the number of steps
3853 # @param MakeGroups forces the generation of new groups from existing ones
3854 # @param scaleFactors optional scale factors to apply during extrusion
3855 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3856 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3857 # @param basePoint optional scaling center; if not provided, a gravity center of
3858 # nodes and elements being extruded is used as the scaling center.
3860 # - a list of tree components of the point or
3863 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3864 # @ingroup l2_modif_extrurev
3865 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3866 scaleFactors=[], linearVariation=False, basePoint=[] ):
3867 unRegister = genObjUnRegister()
3868 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3869 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3870 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3872 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3873 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3874 if isinstance( StepVector, list ):
3875 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3877 if isinstance( basePoint, int):
3878 xyz = self.GetNodeXYZ( basePoint )
3880 raise RuntimeError, "Invalid node ID: %s" % basePoint
3882 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3883 basePoint = self.geompyD.PointCoordinates( basePoint )
3885 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3886 Parameters = StepVector.PS.parameters + var_separator + Parameters
3887 self.mesh.SetParameters(Parameters)
3889 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3890 StepVector, NbOfSteps,
3891 scaleFactors, linearVariation, basePoint,
3895 ## Generate new elements by extrusion of the elements with given ids
3896 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3897 # @param StepVector vector or DirStruct or 3 vector components, defining
3898 # the direction and value of extrusion for one step (the total extrusion
3899 # length will be NbOfSteps * ||StepVector||)
3900 # @param NbOfSteps the number of steps
3901 # @param MakeGroups forces the generation of new groups from existing ones
3902 # @param IsNodes is True if elements with given ids are nodes
3903 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3904 # @ingroup l2_modif_extrurev
3905 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3907 if IsNodes: n = IDsOfElements
3908 else : e,f, = IDsOfElements,IDsOfElements
3909 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3911 ## Generate new elements by extrusion along the normal to a discretized surface or wire
3912 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
3913 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
3914 # @param StepSize length of one extrusion step (the total extrusion
3915 # length will be \a NbOfSteps * \a StepSize ).
3916 # @param NbOfSteps number of extrusion steps.
3917 # @param ByAverageNormal if True each node is translated by \a StepSize
3918 # along the average of the normal vectors to the faces sharing the node;
3919 # else each node is translated along the same average normal till
3920 # intersection with the plane got by translation of the face sharing
3921 # the node along its own normal by \a StepSize.
3922 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3923 # for every node of \a Elements.
3924 # @param MakeGroups forces generation of new groups from existing ones.
3925 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3926 # is not yet implemented. This parameter is used if \a Elements contains
3927 # both faces and edges, i.e. \a Elements is a Mesh.
3928 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3929 # empty list otherwise.
3930 # @ingroup l2_modif_extrurev
3931 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3932 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3933 unRegister = genObjUnRegister()
3934 if isinstance( Elements, Mesh ):
3935 Elements = [ Elements.GetMesh() ]
3936 if isinstance( Elements, list ):
3938 raise RuntimeError, "Elements empty!"
3939 if isinstance( Elements[0], int ):
3940 Elements = self.GetIDSource( Elements, SMESH.ALL )
3941 unRegister.set( Elements )
3942 if not isinstance( Elements, list ):
3943 Elements = [ Elements ]
3944 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3945 self.mesh.SetParameters(Parameters)
3946 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3947 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3949 ## Generate new elements by extrusion of the elements or nodes which belong to the object
3950 # @param theObject the object whose elements or nodes should be processed.
3951 # It can be a mesh, a sub-mesh or a group.
3952 # @param StepVector vector or DirStruct or 3 vector components, defining
3953 # the direction and value of extrusion for one step (the total extrusion
3954 # length will be NbOfSteps * ||StepVector||)
3955 # @param NbOfSteps the number of steps
3956 # @param MakeGroups forces the generation of new groups from existing ones
3957 # @param IsNodes is True if elements to extrude are nodes
3958 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3959 # @ingroup l2_modif_extrurev
3960 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3962 if IsNodes: n = theObject
3963 else : e,f, = theObject,theObject
3964 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3966 ## Generate new elements by extrusion of edges which belong to the object
3967 # @param theObject object whose 1D elements should be processed.
3968 # It can be a mesh, a sub-mesh or a group.
3969 # @param StepVector vector or DirStruct or 3 vector components, defining
3970 # the direction and value of extrusion for one step (the total extrusion
3971 # length will be NbOfSteps * ||StepVector||)
3972 # @param NbOfSteps the number of steps
3973 # @param MakeGroups to generate new groups from existing ones
3974 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3975 # @ingroup l2_modif_extrurev
3976 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3977 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3979 ## Generate new elements by extrusion of faces which belong to the object
3980 # @param theObject object whose 2D elements should be processed.
3981 # It can be a mesh, a sub-mesh or a group.
3982 # @param StepVector vector or DirStruct or 3 vector components, defining
3983 # the direction and value of extrusion for one step (the total extrusion
3984 # length will be NbOfSteps * ||StepVector||)
3985 # @param NbOfSteps the number of steps
3986 # @param MakeGroups forces the generation of new groups from existing ones
3987 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3988 # @ingroup l2_modif_extrurev
3989 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3990 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3992 ## Generate new elements by extrusion of the elements with given ids
3993 # @param IDsOfElements is ids of elements
3994 # @param StepVector vector or DirStruct or 3 vector components, defining
3995 # the direction and value of extrusion for one step (the total extrusion
3996 # length will be NbOfSteps * ||StepVector||)
3997 # @param NbOfSteps the number of steps
3998 # @param ExtrFlags sets flags for extrusion
3999 # @param SewTolerance uses for comparing locations of nodes if flag
4000 # EXTRUSION_FLAG_SEW is set
4001 # @param MakeGroups forces the generation of new groups from existing ones
4002 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4003 # @ingroup l2_modif_extrurev
4004 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4005 ExtrFlags, SewTolerance, MakeGroups=False):
4006 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4007 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4008 if isinstance( StepVector, list ):
4009 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4010 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4011 ExtrFlags, SewTolerance, MakeGroups)
4013 ## Generate new elements by extrusion of the given elements and nodes along the path.
4014 # The path of extrusion must be a meshed edge.
4015 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4016 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4017 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4018 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4019 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4020 # contains not only path segments, else it can be None
4021 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4022 # @param HasAngles allows the shape to be rotated around the path
4023 # to get the resulting mesh in a helical fashion
4024 # @param Angles list of angles
4025 # @param LinearVariation forces the computation of rotation angles as linear
4026 # variation of the given Angles along path steps
4027 # @param HasRefPoint allows using the reference point
4028 # @param RefPoint the point around which the shape is rotated (the mass center of the
4029 # shape by default). The User can specify any point as the Reference Point.
4030 # @param MakeGroups forces the generation of new groups from existing ones
4031 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4032 # @ingroup l2_modif_extrurev
4033 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4034 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4035 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4036 unRegister = genObjUnRegister()
4037 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4038 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4039 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4041 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4042 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4043 if isinstance( RefPoint, list ):
4044 if not RefPoint: RefPoint = [0,0,0]
4045 RefPoint = SMESH.PointStruct( *RefPoint )
4046 if isinstance( PathMesh, Mesh ):
4047 PathMesh = PathMesh.GetMesh()
4048 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4049 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4050 self.mesh.SetParameters(Parameters)
4051 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4052 PathMesh, PathShape, NodeStart,
4053 HasAngles, Angles, LinearVariation,
4054 HasRefPoint, RefPoint, MakeGroups)
4056 ## Generate new elements by extrusion of the given elements
4057 # The path of extrusion must be a meshed edge.
4058 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4059 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4060 # @param NodeStart the start node from Path. Defines the direction of extrusion
4061 # @param HasAngles allows the shape to be rotated around the path
4062 # to get the resulting mesh in a helical fashion
4063 # @param Angles list of angles in radians
4064 # @param LinearVariation forces the computation of rotation angles as linear
4065 # variation of the given Angles along path steps
4066 # @param HasRefPoint allows using the reference point
4067 # @param RefPoint the point around which the elements are rotated (the mass
4068 # center of the elements by default).
4069 # The User can specify any point as the Reference Point.
4070 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4071 # @param MakeGroups forces the generation of new groups from existing ones
4072 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4073 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4074 # only SMESH::Extrusion_Error otherwise
4075 # @ingroup l2_modif_extrurev
4076 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4077 HasAngles=False, Angles=[], LinearVariation=False,
4078 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4079 ElemType=SMESH.FACE):
4081 if ElemType == SMESH.NODE: n = Base
4082 if ElemType == SMESH.EDGE: e = Base
4083 if ElemType == SMESH.FACE: f = Base
4084 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4085 HasAngles, Angles, LinearVariation,
4086 HasRefPoint, RefPoint, MakeGroups)
4087 if MakeGroups: return gr,er
4090 ## Generate new elements by extrusion of the given elements
4091 # The path of extrusion must be a meshed edge.
4092 # @param IDsOfElements ids of elements
4093 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4094 # @param PathShape shape(edge) defines the sub-mesh for the path
4095 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4096 # @param HasAngles allows the shape to be rotated around the path
4097 # to get the resulting mesh in a helical fashion
4098 # @param Angles list of angles in radians
4099 # @param HasRefPoint allows using the reference point
4100 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4101 # The User can specify any point as the Reference Point.
4102 # @param MakeGroups forces the generation of new groups from existing ones
4103 # @param LinearVariation forces the computation of rotation angles as linear
4104 # variation of the given Angles along path steps
4105 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4106 # only SMESH::Extrusion_Error otherwise
4107 # @ingroup l2_modif_extrurev
4108 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4109 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4110 MakeGroups=False, LinearVariation=False):
4111 n,e,f = [],IDsOfElements,IDsOfElements
4112 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4113 NodeStart, HasAngles, Angles,
4115 HasRefPoint, RefPoint, MakeGroups)
4116 if MakeGroups: return gr,er
4119 ## Generate new elements by extrusion of the elements which belong to the object
4120 # The path of extrusion must be a meshed edge.
4121 # @param theObject the object whose elements should be processed.
4122 # It can be a mesh, a sub-mesh or a group.
4123 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4124 # @param PathShape shape(edge) defines the sub-mesh for the path
4125 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4126 # @param HasAngles allows the shape to be rotated around the path
4127 # to get the resulting mesh in a helical fashion
4128 # @param Angles list of angles
4129 # @param HasRefPoint allows using the reference point
4130 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4131 # The User can specify any point as the Reference Point.
4132 # @param MakeGroups forces the generation of new groups from existing ones
4133 # @param LinearVariation forces the computation of rotation angles as linear
4134 # variation of the given Angles along path steps
4135 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4136 # only SMESH::Extrusion_Error otherwise
4137 # @ingroup l2_modif_extrurev
4138 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4139 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4140 MakeGroups=False, LinearVariation=False):
4141 n,e,f = [],theObject,theObject
4142 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4143 HasAngles, Angles, LinearVariation,
4144 HasRefPoint, RefPoint, MakeGroups)
4145 if MakeGroups: return gr,er
4148 ## Generate new elements by extrusion of mesh segments which belong to the object
4149 # The path of extrusion must be a meshed edge.
4150 # @param theObject the object whose 1D elements should be processed.
4151 # It can be a mesh, a sub-mesh or a group.
4152 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4153 # @param PathShape shape(edge) defines the sub-mesh for the path
4154 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4155 # @param HasAngles allows the shape to be rotated around the path
4156 # to get the resulting mesh in a helical fashion
4157 # @param Angles list of angles
4158 # @param HasRefPoint allows using the reference point
4159 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4160 # The User can specify any point as the Reference Point.
4161 # @param MakeGroups forces the generation of new groups from existing ones
4162 # @param LinearVariation forces the computation of rotation angles as linear
4163 # variation of the given Angles along path steps
4164 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4165 # only SMESH::Extrusion_Error otherwise
4166 # @ingroup l2_modif_extrurev
4167 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4168 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4169 MakeGroups=False, LinearVariation=False):
4170 n,e,f = [],theObject,[]
4171 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4172 HasAngles, Angles, LinearVariation,
4173 HasRefPoint, RefPoint, MakeGroups)
4174 if MakeGroups: return gr,er
4177 ## Generate new elements by extrusion of faces which belong to the object
4178 # The path of extrusion must be a meshed edge.
4179 # @param theObject the object whose 2D elements should be processed.
4180 # It can be a mesh, a sub-mesh or a group.
4181 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4182 # @param PathShape shape(edge) defines the sub-mesh for the path
4183 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4184 # @param HasAngles allows the shape to be rotated around the path
4185 # to get the resulting mesh in a helical fashion
4186 # @param Angles list of angles
4187 # @param HasRefPoint allows using the reference point
4188 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4189 # The User can specify any point as the Reference Point.
4190 # @param MakeGroups forces the generation of new groups from existing ones
4191 # @param LinearVariation forces the computation of rotation angles as linear
4192 # variation of the given Angles along path steps
4193 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4194 # only SMESH::Extrusion_Error otherwise
4195 # @ingroup l2_modif_extrurev
4196 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4197 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4198 MakeGroups=False, LinearVariation=False):
4199 n,e,f = [],[],theObject
4200 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4201 HasAngles, Angles, LinearVariation,
4202 HasRefPoint, RefPoint, MakeGroups)
4203 if MakeGroups: return gr,er
4206 ## Create a symmetrical copy of mesh elements
4207 # @param IDsOfElements list of elements ids
4208 # @param Mirror is AxisStruct or geom object(point, line, plane)
4209 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4210 # If the Mirror is a geom object this parameter is unnecessary
4211 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4212 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4213 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4214 # @ingroup l2_modif_trsf
4215 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4216 if IDsOfElements == []:
4217 IDsOfElements = self.GetElementsId()
4218 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4219 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4220 theMirrorType = Mirror._mirrorType
4222 self.mesh.SetParameters(Mirror.parameters)
4223 if Copy and MakeGroups:
4224 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4225 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4228 ## Create a new mesh by a symmetrical copy of mesh elements
4229 # @param IDsOfElements the list of elements ids
4230 # @param Mirror is AxisStruct or geom object (point, line, plane)
4231 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4232 # If the Mirror is a geom object this parameter is unnecessary
4233 # @param MakeGroups to generate new groups from existing ones
4234 # @param NewMeshName a name of the new mesh to create
4235 # @return instance of Mesh class
4236 # @ingroup l2_modif_trsf
4237 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4238 if IDsOfElements == []:
4239 IDsOfElements = self.GetElementsId()
4240 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4241 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4242 theMirrorType = Mirror._mirrorType
4244 self.mesh.SetParameters(Mirror.parameters)
4245 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4246 MakeGroups, NewMeshName)
4247 return Mesh(self.smeshpyD,self.geompyD,mesh)
4249 ## Create a symmetrical copy of the object
4250 # @param theObject mesh, submesh or group
4251 # @param Mirror AxisStruct or geom object (point, line, plane)
4252 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4253 # If the Mirror is a geom object this parameter is unnecessary
4254 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4255 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4256 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4257 # @ingroup l2_modif_trsf
4258 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4259 if ( isinstance( theObject, Mesh )):
4260 theObject = theObject.GetMesh()
4261 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4262 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4263 theMirrorType = Mirror._mirrorType
4265 self.mesh.SetParameters(Mirror.parameters)
4266 if Copy and MakeGroups:
4267 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4268 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4271 ## Create a new mesh by a symmetrical copy of the object
4272 # @param theObject mesh, submesh or group
4273 # @param Mirror AxisStruct or geom object (point, line, plane)
4274 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4275 # If the Mirror is a geom object this parameter is unnecessary
4276 # @param MakeGroups forces the generation of new groups from existing ones
4277 # @param NewMeshName the name of the new mesh to create
4278 # @return instance of Mesh class
4279 # @ingroup l2_modif_trsf
4280 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4281 if ( isinstance( theObject, Mesh )):
4282 theObject = theObject.GetMesh()
4283 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4284 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4285 theMirrorType = Mirror._mirrorType
4287 self.mesh.SetParameters(Mirror.parameters)
4288 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4289 MakeGroups, NewMeshName)
4290 return Mesh( self.smeshpyD,self.geompyD,mesh )
4292 ## Translate the elements
4293 # @param IDsOfElements list of elements ids
4294 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4295 # @param Copy allows copying the translated elements
4296 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4297 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4298 # @ingroup l2_modif_trsf
4299 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4300 if IDsOfElements == []:
4301 IDsOfElements = self.GetElementsId()
4302 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4303 Vector = self.smeshpyD.GetDirStruct(Vector)
4304 if isinstance( Vector, list ):
4305 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4306 self.mesh.SetParameters(Vector.PS.parameters)
4307 if Copy and MakeGroups:
4308 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4309 self.editor.Translate(IDsOfElements, Vector, Copy)
4312 ## Create a new mesh of translated elements
4313 # @param IDsOfElements list of elements ids
4314 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4315 # @param MakeGroups forces the generation of new groups from existing ones
4316 # @param NewMeshName the name of the newly created mesh
4317 # @return instance of Mesh class
4318 # @ingroup l2_modif_trsf
4319 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4320 if IDsOfElements == []:
4321 IDsOfElements = self.GetElementsId()
4322 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4323 Vector = self.smeshpyD.GetDirStruct(Vector)
4324 if isinstance( Vector, list ):
4325 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4326 self.mesh.SetParameters(Vector.PS.parameters)
4327 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4328 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4330 ## Translate the object
4331 # @param theObject the object to translate (mesh, submesh, or group)
4332 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4333 # @param Copy allows copying the translated elements
4334 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4335 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4336 # @ingroup l2_modif_trsf
4337 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4338 if ( isinstance( theObject, Mesh )):
4339 theObject = theObject.GetMesh()
4340 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4341 Vector = self.smeshpyD.GetDirStruct(Vector)
4342 if isinstance( Vector, list ):
4343 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4344 self.mesh.SetParameters(Vector.PS.parameters)
4345 if Copy and MakeGroups:
4346 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4347 self.editor.TranslateObject(theObject, Vector, Copy)
4350 ## Create a new mesh from the translated object
4351 # @param theObject the object to translate (mesh, submesh, or group)
4352 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4353 # @param MakeGroups forces the generation of new groups from existing ones
4354 # @param NewMeshName the name of the newly created mesh
4355 # @return instance of Mesh class
4356 # @ingroup l2_modif_trsf
4357 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4358 if isinstance( theObject, Mesh ):
4359 theObject = theObject.GetMesh()
4360 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4361 Vector = self.smeshpyD.GetDirStruct(Vector)
4362 if isinstance( Vector, list ):
4363 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4364 self.mesh.SetParameters(Vector.PS.parameters)
4365 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4366 return Mesh( self.smeshpyD, self.geompyD, mesh )
4371 # @param theObject - the object to translate (mesh, submesh, or group)
4372 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4373 # @param theScaleFact - list of 1-3 scale factors for axises
4374 # @param Copy - allows copying the translated elements
4375 # @param MakeGroups - forces the generation of new groups from existing
4377 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4378 # empty list otherwise
4379 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4380 unRegister = genObjUnRegister()
4381 if ( isinstance( theObject, Mesh )):
4382 theObject = theObject.GetMesh()
4383 if ( isinstance( theObject, list )):
4384 theObject = self.GetIDSource(theObject, SMESH.ALL)
4385 unRegister.set( theObject )
4386 if ( isinstance( thePoint, list )):
4387 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4388 if ( isinstance( theScaleFact, float )):
4389 theScaleFact = [theScaleFact]
4390 if ( isinstance( theScaleFact, int )):
4391 theScaleFact = [ float(theScaleFact)]
4393 self.mesh.SetParameters(thePoint.parameters)
4395 if Copy and MakeGroups:
4396 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4397 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4400 ## Create a new mesh from the translated object
4401 # @param theObject - the object to translate (mesh, submesh, or group)
4402 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4403 # @param theScaleFact - list of 1-3 scale factors for axises
4404 # @param MakeGroups - forces the generation of new groups from existing ones
4405 # @param NewMeshName - the name of the newly created mesh
4406 # @return instance of Mesh class
4407 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4408 unRegister = genObjUnRegister()
4409 if (isinstance(theObject, Mesh)):
4410 theObject = theObject.GetMesh()
4411 if ( isinstance( theObject, list )):
4412 theObject = self.GetIDSource(theObject,SMESH.ALL)
4413 unRegister.set( theObject )
4414 if ( isinstance( thePoint, list )):
4415 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4416 if ( isinstance( theScaleFact, float )):
4417 theScaleFact = [theScaleFact]
4418 if ( isinstance( theScaleFact, int )):
4419 theScaleFact = [ float(theScaleFact)]
4421 self.mesh.SetParameters(thePoint.parameters)
4422 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4423 MakeGroups, NewMeshName)
4424 return Mesh( self.smeshpyD, self.geompyD, mesh )
4428 ## Rotate the elements
4429 # @param IDsOfElements list of elements ids
4430 # @param Axis the axis of rotation (AxisStruct or geom line)
4431 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4432 # @param Copy allows copying the rotated elements
4433 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4434 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4435 # @ingroup l2_modif_trsf
4436 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4437 if IDsOfElements == []:
4438 IDsOfElements = self.GetElementsId()
4439 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4440 Axis = self.smeshpyD.GetAxisStruct(Axis)
4441 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4442 Parameters = Axis.parameters + var_separator + Parameters
4443 self.mesh.SetParameters(Parameters)
4444 if Copy and MakeGroups:
4445 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4446 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4449 ## Create a new mesh of rotated elements
4450 # @param IDsOfElements list of element ids
4451 # @param Axis the axis of rotation (AxisStruct or geom line)
4452 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4453 # @param MakeGroups forces the generation of new groups from existing ones
4454 # @param NewMeshName the name of the newly created mesh
4455 # @return instance of Mesh class
4456 # @ingroup l2_modif_trsf
4457 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4458 if IDsOfElements == []:
4459 IDsOfElements = self.GetElementsId()
4460 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4461 Axis = self.smeshpyD.GetAxisStruct(Axis)
4462 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4463 Parameters = Axis.parameters + var_separator + Parameters
4464 self.mesh.SetParameters(Parameters)
4465 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4466 MakeGroups, NewMeshName)
4467 return Mesh( self.smeshpyD, self.geompyD, mesh )
4469 ## Rotate the object
4470 # @param theObject the object to rotate( mesh, submesh, or group)
4471 # @param Axis the axis of rotation (AxisStruct or geom line)
4472 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4473 # @param Copy allows copying the rotated elements
4474 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4475 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4476 # @ingroup l2_modif_trsf
4477 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4478 if (isinstance(theObject, Mesh)):
4479 theObject = theObject.GetMesh()
4480 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4481 Axis = self.smeshpyD.GetAxisStruct(Axis)
4482 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4483 Parameters = Axis.parameters + ":" + Parameters
4484 self.mesh.SetParameters(Parameters)
4485 if Copy and MakeGroups:
4486 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4487 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4490 ## Create a new mesh from the rotated object
4491 # @param theObject the object to rotate (mesh, submesh, or group)
4492 # @param Axis the axis of rotation (AxisStruct or geom line)
4493 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4494 # @param MakeGroups forces the generation of new groups from existing ones
4495 # @param NewMeshName the name of the newly created mesh
4496 # @return instance of Mesh class
4497 # @ingroup l2_modif_trsf
4498 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4499 if (isinstance( theObject, Mesh )):
4500 theObject = theObject.GetMesh()
4501 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4502 Axis = self.smeshpyD.GetAxisStruct(Axis)
4503 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4504 Parameters = Axis.parameters + ":" + Parameters
4505 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4506 MakeGroups, NewMeshName)
4507 self.mesh.SetParameters(Parameters)
4508 return Mesh( self.smeshpyD, self.geompyD, mesh )
4510 ## Find groups of adjacent nodes within Tolerance.
4511 # @param Tolerance the value of tolerance
4512 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4513 # corner and medium nodes in separate groups thus preventing
4514 # their further merge.
4515 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4516 # @ingroup l2_modif_trsf
4517 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4518 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4520 ## Find groups of ajacent nodes within Tolerance.
4521 # @param Tolerance the value of tolerance
4522 # @param SubMeshOrGroup SubMesh, Group or Filter
4523 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4524 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4525 # corner and medium nodes in separate groups thus preventing
4526 # their further merge.
4527 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4528 # @ingroup l2_modif_trsf
4529 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4530 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4531 unRegister = genObjUnRegister()
4532 if (isinstance( SubMeshOrGroup, Mesh )):
4533 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4534 if not isinstance( exceptNodes, list ):
4535 exceptNodes = [ exceptNodes ]
4536 if exceptNodes and isinstance( exceptNodes[0], int ):
4537 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4538 unRegister.set( exceptNodes )
4539 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4540 exceptNodes, SeparateCornerAndMediumNodes)
4543 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4544 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4545 # by nodes 1 and 25 correspondingly in all elements and groups
4546 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4547 # If @a NodesToKeep does not include a node to keep for some group to merge,
4548 # then the first node in the group is kept.
4549 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4551 # @ingroup l2_modif_trsf
4552 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4553 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4554 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4556 ## Find the elements built on the same nodes.
4557 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4558 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4559 # @ingroup l2_modif_trsf
4560 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4561 if not MeshOrSubMeshOrGroup:
4562 MeshOrSubMeshOrGroup=self.mesh
4563 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4564 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4565 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4567 ## Merge elements in each given group.
4568 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4569 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4570 # replaced by elements 1 and 25 in all groups)
4571 # @ingroup l2_modif_trsf
4572 def MergeElements(self, GroupsOfElementsID):
4573 self.editor.MergeElements(GroupsOfElementsID)
4575 ## Leave one element and remove all other elements built on the same nodes.
4576 # @ingroup l2_modif_trsf
4577 def MergeEqualElements(self):
4578 self.editor.MergeEqualElements()
4580 ## Return groups of FreeBorder's coincident within the given tolerance.
4581 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4582 # size of elements adjacent to free borders being compared is used.
4583 # @return SMESH.CoincidentFreeBorders structure
4584 # @ingroup l2_modif_trsf
4585 def FindCoincidentFreeBorders (self, tolerance=0.):
4586 return self.editor.FindCoincidentFreeBorders( tolerance )
4588 ## Sew FreeBorder's of each group
4589 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4590 # where each enclosed list contains node IDs of a group of coincident free
4591 # borders such that each consequent triple of IDs within a group describes
4592 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4593 # last node of a border.
4594 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4595 # groups of coincident free borders, each group including two borders.
4596 # @param createPolygons if @c True faces adjacent to free borders are converted to
4597 # polygons if a node of opposite border falls on a face edge, else such
4598 # faces are split into several ones.
4599 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4600 # polyhedra if a node of opposite border falls on a volume edge, else such
4601 # volumes, if any, remain intact and the mesh becomes non-conformal.
4602 # @return a number of successfully sewed groups
4603 # @ingroup l2_modif_trsf
4604 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4605 if freeBorders and isinstance( freeBorders, list ):
4606 # construct SMESH.CoincidentFreeBorders
4607 if isinstance( freeBorders[0], int ):
4608 freeBorders = [freeBorders]
4610 coincidentGroups = []
4611 for nodeList in freeBorders:
4612 if not nodeList or len( nodeList ) % 3:
4613 raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
4616 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4617 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4618 nodeList = nodeList[3:]
4620 coincidentGroups.append( group )
4622 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4624 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4627 # @return SMESH::Sew_Error
4628 # @ingroup l2_modif_trsf
4629 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4630 FirstNodeID2, SecondNodeID2, LastNodeID2,
4631 CreatePolygons, CreatePolyedrs):
4632 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4633 FirstNodeID2, SecondNodeID2, LastNodeID2,
4634 CreatePolygons, CreatePolyedrs)
4636 ## Sew conform free borders
4637 # @return SMESH::Sew_Error
4638 # @ingroup l2_modif_trsf
4639 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4640 FirstNodeID2, SecondNodeID2):
4641 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4642 FirstNodeID2, SecondNodeID2)
4644 ## Sew border to side
4645 # @return SMESH::Sew_Error
4646 # @ingroup l2_modif_trsf
4647 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4648 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4649 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4650 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4652 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4653 # merged with the nodes of elements of Side2.
4654 # The number of elements in theSide1 and in theSide2 must be
4655 # equal and they should have similar nodal connectivity.
4656 # The nodes to merge should belong to side borders and
4657 # the first node should be linked to the second.
4658 # @return SMESH::Sew_Error
4659 # @ingroup l2_modif_trsf
4660 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4661 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4662 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4663 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4664 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4665 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4667 ## Set new nodes for the given element.
4668 # @param ide the element id
4669 # @param newIDs nodes ids
4670 # @return If the number of nodes does not correspond to the type of element - return false
4671 # @ingroup l2_modif_edit
4672 def ChangeElemNodes(self, ide, newIDs):
4673 return self.editor.ChangeElemNodes(ide, newIDs)
4675 ## If during the last operation of MeshEditor some nodes were
4676 # created, this method return the list of their IDs, \n
4677 # if new nodes were not created - return empty list
4678 # @return the list of integer values (can be empty)
4679 # @ingroup l2_modif_add
4680 def GetLastCreatedNodes(self):
4681 return self.editor.GetLastCreatedNodes()
4683 ## If during the last operation of MeshEditor some elements were
4684 # created this method return the list of their IDs, \n
4685 # if new elements were not created - return empty list
4686 # @return the list of integer values (can be empty)
4687 # @ingroup l2_modif_add
4688 def GetLastCreatedElems(self):
4689 return self.editor.GetLastCreatedElems()
4691 ## Forget what nodes and elements were created by the last mesh edition operation
4692 # @ingroup l2_modif_add
4693 def ClearLastCreated(self):
4694 self.editor.ClearLastCreated()
4696 ## Create duplicates of given elements, i.e. create new elements based on the
4697 # same nodes as the given ones.
4698 # @param theElements - container of elements to duplicate. It can be a Mesh,
4699 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4700 # a Mesh, elements of highest dimension are duplicated
4701 # @param theGroupName - a name of group to contain the generated elements.
4702 # If a group with such a name already exists, the new elements
4703 # are added to the existng group, else a new group is created.
4704 # If \a theGroupName is empty, new elements are not added
4706 # @return a group where the new elements are added. None if theGroupName == "".
4707 # @ingroup l2_modif_duplicat
4708 def DoubleElements(self, theElements, theGroupName=""):
4709 unRegister = genObjUnRegister()
4710 if isinstance( theElements, Mesh ):
4711 theElements = theElements.mesh
4712 elif isinstance( theElements, list ):
4713 theElements = self.GetIDSource( theElements, SMESH.ALL )
4714 unRegister.set( theElements )
4715 return self.editor.DoubleElements(theElements, theGroupName)
4717 ## Create a hole in a mesh by doubling the nodes of some particular elements
4718 # @param theNodes identifiers of nodes to be doubled
4719 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4720 # nodes. If list of element identifiers is empty then nodes are doubled but
4721 # they not assigned to elements
4722 # @return TRUE if operation has been completed successfully, FALSE otherwise
4723 # @ingroup l2_modif_duplicat
4724 def DoubleNodes(self, theNodes, theModifiedElems):
4725 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4727 ## Create a hole in a mesh by doubling the nodes of some particular elements
4728 # This method provided for convenience works as DoubleNodes() described above.
4729 # @param theNodeId identifiers of node to be doubled
4730 # @param theModifiedElems identifiers of elements to be updated
4731 # @return TRUE if operation has been completed successfully, FALSE otherwise
4732 # @ingroup l2_modif_duplicat
4733 def DoubleNode(self, theNodeId, theModifiedElems):
4734 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4736 ## Create a hole in a mesh by doubling the nodes of some particular elements
4737 # This method provided for convenience works as DoubleNodes() described above.
4738 # @param theNodes group of nodes to be doubled
4739 # @param theModifiedElems group of elements to be updated.
4740 # @param theMakeGroup forces the generation of a group containing new nodes.
4741 # @return TRUE or a created group if operation has been completed successfully,
4742 # FALSE or None otherwise
4743 # @ingroup l2_modif_duplicat
4744 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4746 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4747 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4749 ## Create a hole in a mesh by doubling the nodes of some particular elements
4750 # This method provided for convenience works as DoubleNodes() described above.
4751 # @param theNodes list of groups of nodes to be doubled
4752 # @param theModifiedElems list of groups of elements to be updated.
4753 # @param theMakeGroup forces the generation of a group containing new nodes.
4754 # @return TRUE if operation has been completed successfully, FALSE otherwise
4755 # @ingroup l2_modif_duplicat
4756 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4758 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4759 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4761 ## Create a hole in a mesh by doubling the nodes of some particular elements
4762 # @param theElems - the list of elements (edges or faces) to be replicated
4763 # The nodes for duplication could be found from these elements
4764 # @param theNodesNot - list of nodes to NOT replicate
4765 # @param theAffectedElems - the list of elements (cells and edges) to which the
4766 # replicated nodes should be associated to.
4767 # @return TRUE if operation has been completed successfully, FALSE otherwise
4768 # @ingroup l2_modif_duplicat
4769 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4770 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4772 ## Create a hole in a mesh by doubling the nodes of some particular elements
4773 # @param theElems - the list of elements (edges or faces) to be replicated
4774 # The nodes for duplication could be found from these elements
4775 # @param theNodesNot - list of nodes to NOT replicate
4776 # @param theShape - shape to detect affected elements (element which geometric center
4777 # located on or inside shape).
4778 # The replicated nodes should be associated to affected elements.
4779 # @return TRUE if operation has been completed successfully, FALSE otherwise
4780 # @ingroup l2_modif_duplicat
4781 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4782 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4784 ## Create a hole in a mesh by doubling the nodes of some particular elements
4785 # This method provided for convenience works as DoubleNodes() described above.
4786 # @param theElems - group of of elements (edges or faces) to be replicated
4787 # @param theNodesNot - group of nodes not to replicated
4788 # @param theAffectedElems - group of elements to which the replicated nodes
4789 # should be associated to.
4790 # @param theMakeGroup forces the generation of a group containing new elements.
4791 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4792 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4793 # FALSE or None otherwise
4794 # @ingroup l2_modif_duplicat
4795 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4796 theMakeGroup=False, theMakeNodeGroup=False):
4797 if theMakeGroup or theMakeNodeGroup:
4798 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4800 theMakeGroup, theMakeNodeGroup)
4801 if theMakeGroup and theMakeNodeGroup:
4804 return twoGroups[ int(theMakeNodeGroup) ]
4805 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4807 ## Create a hole in a mesh by doubling the nodes of some particular elements
4808 # This method provided for convenience works as DoubleNodes() described above.
4809 # @param theElems - group of of elements (edges or faces) to be replicated
4810 # @param theNodesNot - group of nodes not to replicated
4811 # @param theShape - shape to detect affected elements (element which geometric center
4812 # located on or inside shape).
4813 # The replicated nodes should be associated to affected elements.
4814 # @ingroup l2_modif_duplicat
4815 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4816 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4818 ## Create a hole in a mesh by doubling the nodes of some particular elements
4819 # This method provided for convenience works as DoubleNodes() described above.
4820 # @param theElems - list of groups of elements (edges or faces) to be replicated
4821 # @param theNodesNot - list of groups of nodes not to replicated
4822 # @param theAffectedElems - group of elements to which the replicated nodes
4823 # should be associated to.
4824 # @param theMakeGroup forces the generation of a group containing new elements.
4825 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4826 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4827 # FALSE or None otherwise
4828 # @ingroup l2_modif_duplicat
4829 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4830 theMakeGroup=False, theMakeNodeGroup=False):
4831 if theMakeGroup or theMakeNodeGroup:
4832 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4834 theMakeGroup, theMakeNodeGroup)
4835 if theMakeGroup and theMakeNodeGroup:
4838 return twoGroups[ int(theMakeNodeGroup) ]
4839 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4841 ## Create a hole in a mesh by doubling the nodes of some particular elements
4842 # This method provided for convenience works as DoubleNodes() described above.
4843 # @param theElems - list of groups of elements (edges or faces) to be replicated
4844 # @param theNodesNot - list of groups of nodes not to replicated
4845 # @param theShape - shape to detect affected elements (element which geometric center
4846 # located on or inside shape).
4847 # The replicated nodes should be associated to affected elements.
4848 # @return TRUE if operation has been completed successfully, FALSE otherwise
4849 # @ingroup l2_modif_duplicat
4850 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4851 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4853 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4854 # This method is the first step of DoubleNodeElemGroupsInRegion.
4855 # @param theElems - list of groups of elements (edges or faces) to be replicated
4856 # @param theNodesNot - list of groups of nodes not to replicated
4857 # @param theShape - shape to detect affected elements (element which geometric center
4858 # located on or inside shape).
4859 # The replicated nodes should be associated to affected elements.
4860 # @return groups of affected elements
4861 # @ingroup l2_modif_duplicat
4862 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4863 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4865 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4866 # The list of groups must describe a partition of the mesh volumes.
4867 # The nodes of the internal faces at the boundaries of the groups are doubled.
4868 # In option, the internal faces are replaced by flat elements.
4869 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4870 # @param theDomains - list of groups of volumes
4871 # @param createJointElems - if TRUE, create the elements
4872 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4873 # the boundary between \a theDomains and the rest mesh
4874 # @return TRUE if operation has been completed successfully, FALSE otherwise
4875 # @ingroup l2_modif_duplicat
4876 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4877 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4879 ## Double nodes on some external faces and create flat elements.
4880 # Flat elements are mainly used by some types of mechanic calculations.
4882 # Each group of the list must be constituted of faces.
4883 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4884 # @param theGroupsOfFaces - list of groups of faces
4885 # @return TRUE if operation has been completed successfully, FALSE otherwise
4886 # @ingroup l2_modif_duplicat
4887 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4888 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4890 ## identify all the elements around a geom shape, get the faces delimiting the hole
4892 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4893 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4895 def _getFunctor(self, funcType ):
4896 fn = self.functors[ funcType._v ]
4898 fn = self.smeshpyD.GetFunctor(funcType)
4899 fn.SetMesh(self.mesh)
4900 self.functors[ funcType._v ] = fn
4903 ## Return value of a functor for a given element
4904 # @param funcType an item of SMESH.FunctorType enum
4905 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4906 # @param elemId element or node ID
4907 # @param isElem @a elemId is ID of element or node
4908 # @return the functor value or zero in case of invalid arguments
4909 # @ingroup l1_measurements
4910 def FunctorValue(self, funcType, elemId, isElem=True):
4911 fn = self._getFunctor( funcType )
4912 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4913 val = fn.GetValue(elemId)
4918 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4919 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4920 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4921 # @ingroup l1_measurements
4922 def GetLength(self, elemId=None):
4925 length = self.smeshpyD.GetLength(self)
4927 length = self.FunctorValue(SMESH.FT_Length, elemId)
4930 ## Get area of 2D element or sum of areas of all 2D mesh elements
4931 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4932 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4933 # @ingroup l1_measurements
4934 def GetArea(self, elemId=None):
4937 area = self.smeshpyD.GetArea(self)
4939 area = self.FunctorValue(SMESH.FT_Area, elemId)
4942 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4943 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4944 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4945 # @ingroup l1_measurements
4946 def GetVolume(self, elemId=None):
4949 volume = self.smeshpyD.GetVolume(self)
4951 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4954 ## Get maximum element length.
4955 # @param elemId mesh element ID
4956 # @return element's maximum length value
4957 # @ingroup l1_measurements
4958 def GetMaxElementLength(self, elemId):
4959 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4960 ftype = SMESH.FT_MaxElementLength3D
4962 ftype = SMESH.FT_MaxElementLength2D
4963 return self.FunctorValue(ftype, elemId)
4965 ## Get aspect ratio of 2D or 3D element.
4966 # @param elemId mesh element ID
4967 # @return element's aspect ratio value
4968 # @ingroup l1_measurements
4969 def GetAspectRatio(self, elemId):
4970 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4971 ftype = SMESH.FT_AspectRatio3D
4973 ftype = SMESH.FT_AspectRatio
4974 return self.FunctorValue(ftype, elemId)
4976 ## Get warping angle of 2D element.
4977 # @param elemId mesh element ID
4978 # @return element's warping angle value
4979 # @ingroup l1_measurements
4980 def GetWarping(self, elemId):
4981 return self.FunctorValue(SMESH.FT_Warping, elemId)
4983 ## Get minimum angle of 2D element.
4984 # @param elemId mesh element ID
4985 # @return element's minimum angle value
4986 # @ingroup l1_measurements
4987 def GetMinimumAngle(self, elemId):
4988 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4990 ## Get taper of 2D element.
4991 # @param elemId mesh element ID
4992 # @return element's taper value
4993 # @ingroup l1_measurements
4994 def GetTaper(self, elemId):
4995 return self.FunctorValue(SMESH.FT_Taper, elemId)
4997 ## Get skew of 2D element.
4998 # @param elemId mesh element ID
4999 # @return element's skew value
5000 # @ingroup l1_measurements
5001 def GetSkew(self, elemId):
5002 return self.FunctorValue(SMESH.FT_Skew, elemId)
5004 ## Return minimal and maximal value of a given functor.
5005 # @param funType a functor type, an item of SMESH.FunctorType enum
5006 # (one of SMESH.FunctorType._items)
5007 # @param meshPart a part of mesh (group, sub-mesh) to treat
5008 # @return tuple (min,max)
5009 # @ingroup l1_measurements
5010 def GetMinMax(self, funType, meshPart=None):
5011 unRegister = genObjUnRegister()
5012 if isinstance( meshPart, list ):
5013 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5014 unRegister.set( meshPart )
5015 if isinstance( meshPart, Mesh ):
5016 meshPart = meshPart.mesh
5017 fun = self._getFunctor( funType )
5020 if hasattr( meshPart, "SetMesh" ):
5021 meshPart.SetMesh( self.mesh ) # set mesh to filter
5022 hist = fun.GetLocalHistogram( 1, False, meshPart )
5024 hist = fun.GetHistogram( 1, False )
5026 return hist[0].min, hist[0].max
5029 pass # end of Mesh class
5032 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5033 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5035 class meshProxy(SMESH._objref_SMESH_Mesh):
5037 SMESH._objref_SMESH_Mesh.__init__(self)
5038 def __deepcopy__(self, memo=None):
5039 new = self.__class__()
5041 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5042 if len( args ) == 3:
5043 args += SMESH.ALL_NODES, True
5044 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5046 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5049 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5051 class submeshProxy(SMESH._objref_SMESH_subMesh):
5053 SMESH._objref_SMESH_subMesh.__init__(self)
5055 def __deepcopy__(self, memo=None):
5056 new = self.__class__()
5059 ## Compute the sub-mesh and return the status of the computation
5060 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5061 # @return True or False
5063 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5064 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5065 # @ingroup l2_submeshes
5066 def Compute(self,refresh=False):
5068 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5070 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5072 if salome.sg.hasDesktop():
5073 smeshgui = salome.ImportComponentGUI("SMESH")
5075 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5076 if refresh: salome.sg.updateObjBrowser()
5081 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5084 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5085 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5088 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5090 SMESH._objref_SMESH_MeshEditor.__init__(self)
5092 def __getattr__(self, name ): # method called if an attribute not found
5093 if not self.mesh: # look for name() method in Mesh class
5094 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5095 if hasattr( self.mesh, name ):
5096 return getattr( self.mesh, name )
5097 if name == "ExtrusionAlongPathObjX":
5098 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5099 print "meshEditor: attribute '%s' NOT FOUND" % name
5101 def __deepcopy__(self, memo=None):
5102 new = self.__class__()
5104 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5105 if len( args ) == 1: args += False,
5106 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5107 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5108 if len( args ) == 2: args += False,
5109 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5110 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5111 if len( args ) == 1:
5112 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5113 NodesToKeep = args[1]
5114 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5115 unRegister = genObjUnRegister()
5117 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5118 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5119 if not isinstance( NodesToKeep, list ):
5120 NodesToKeep = [ NodesToKeep ]
5121 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5123 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5125 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5126 # variables in some methods
5128 class Pattern(SMESH._objref_SMESH_Pattern):
5130 def LoadFromFile(self, patternTextOrFile ):
5131 text = patternTextOrFile
5132 if os.path.exists( text ):
5133 text = open( patternTextOrFile ).read()
5135 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5137 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5138 decrFun = lambda i: i-1
5139 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5140 theMesh.SetParameters(Parameters)
5141 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5143 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5144 decrFun = lambda i: i-1
5145 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5146 theMesh.SetParameters(Parameters)
5147 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5149 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5150 if isinstance( mesh, Mesh ):
5151 mesh = mesh.GetMesh()
5152 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5154 # Registering the new proxy for Pattern
5155 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5157 ## Private class used to bind methods creating algorithms to the class Mesh
5160 def __init__(self, method):
5162 self.defaultAlgoType = ""
5163 self.algoTypeToClass = {}
5164 self.method = method
5166 # Store a python class of algorithm
5167 def add(self, algoClass):
5168 if type( algoClass ).__name__ == 'classobj' and \
5169 hasattr( algoClass, "algoType"):
5170 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5171 if not self.defaultAlgoType and \
5172 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5173 self.defaultAlgoType = algoClass.algoType
5174 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5176 # Create a copy of self and assign mesh to the copy
5177 def copy(self, mesh):
5178 other = algoCreator( self.method )
5179 other.defaultAlgoType = self.defaultAlgoType
5180 other.algoTypeToClass = self.algoTypeToClass
5184 # Create an instance of algorithm
5185 def __call__(self,algo="",geom=0,*args):
5188 if isinstance( algo, str ):
5190 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
5191 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
5196 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
5198 elif not algoType and isinstance( geom, str ):
5203 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
5205 elif isinstance( arg, str ) and not algoType:
5208 import traceback, sys
5209 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
5210 sys.stderr.write( msg + '\n' )
5211 tb = traceback.extract_stack(None,2)
5212 traceback.print_list( [tb[0]] )
5214 algoType = self.defaultAlgoType
5215 if not algoType and self.algoTypeToClass:
5216 algoType = self.algoTypeToClass.keys()[0]
5217 if self.algoTypeToClass.has_key( algoType ):
5218 #print "Create algo",algoType
5219 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
5220 raise RuntimeError, "No class found for algo type %s" % algoType
5223 ## Private class used to substitute and store variable parameters of hypotheses.
5225 class hypMethodWrapper:
5226 def __init__(self, hyp, method):
5228 self.method = method
5229 #print "REBIND:", method.__name__
5232 # call a method of hypothesis with calling SetVarParameter() before
5233 def __call__(self,*args):
5235 return self.method( self.hyp, *args ) # hypothesis method with no args
5237 #print "MethWrapper.__call__",self.method.__name__, args
5239 parsed = ParseParameters(*args) # replace variables with their values
5240 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5241 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5242 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5243 # maybe there is a replaced string arg which is not variable
5244 result = self.method( self.hyp, *args )
5245 except ValueError, detail: # raised by ParseParameters()
5247 result = self.method( self.hyp, *args )
5248 except omniORB.CORBA.BAD_PARAM:
5249 raise ValueError, detail # wrong variable name
5254 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5256 class genObjUnRegister:
5258 def __init__(self, genObj=None):
5259 self.genObjList = []
5263 def set(self, genObj):
5264 "Store one or a list of of SALOME.GenericObj'es"
5265 if isinstance( genObj, list ):
5266 self.genObjList.extend( genObj )
5268 self.genObjList.append( genObj )
5272 for genObj in self.genObjList:
5273 if genObj and hasattr( genObj, "UnRegister" ):
5277 ## Bind methods creating mesher plug-ins to the Mesh class
5279 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5281 #print "pluginName: ", pluginName
5282 pluginBuilderName = pluginName + "Builder"
5284 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5285 except Exception, e:
5286 from salome_utils import verbose
5287 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5289 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5290 plugin = eval( pluginBuilderName )
5291 #print " plugin:" , str(plugin)
5293 # add methods creating algorithms to Mesh
5294 for k in dir( plugin ):
5295 if k[0] == '_': continue
5296 algo = getattr( plugin, k )
5297 #print " algo:", str(algo)
5298 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5299 #print " meshMethod:" , str(algo.meshMethod)
5300 if not hasattr( Mesh, algo.meshMethod ):
5301 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
5303 getattr( Mesh, algo.meshMethod ).add( algo )