1 # Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
30 ## @defgroup l2_construct Constructing meshes
31 ## @defgroup l2_algorithms Defining Algorithms
33 ## @defgroup l3_algos_basic Basic meshing algorithms
34 ## @defgroup l3_algos_proj Projection Algorithms
35 ## @defgroup l3_algos_radialp Radial Prism
36 ## @defgroup l3_algos_segmarv Segments around Vertex
37 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
40 ## @defgroup l2_hypotheses Defining hypotheses
42 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ## @defgroup l3_hypos_additi Additional Hypotheses
49 ## @defgroup l2_submeshes Constructing submeshes
50 ## @defgroup l2_compounds Building Compounds
51 ## @defgroup l2_editing Editing Meshes
54 ## @defgroup l1_meshinfo Mesh Information
55 ## @defgroup l1_controls Quality controls and Filtering
56 ## @defgroup l1_grouping Grouping elements
58 ## @defgroup l2_grps_create Creating groups
59 ## @defgroup l2_grps_edit Editing groups
60 ## @defgroup l2_grps_operon Using operations on groups
61 ## @defgroup l2_grps_delete Deleting Groups
64 ## @defgroup l1_modifying Modifying meshes
66 ## @defgroup l2_modif_add Adding nodes and elements
67 ## @defgroup l2_modif_del Removing nodes and elements
68 ## @defgroup l2_modif_edit Modifying nodes and elements
69 ## @defgroup l2_modif_renumber Renumbering nodes and elements
70 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ## @defgroup l2_modif_movenode Moving nodes
72 ## @defgroup l2_modif_throughp Mesh through point
73 ## @defgroup l2_modif_invdiag Diagonal inversion of elements
74 ## @defgroup l2_modif_unitetri Uniting triangles
75 ## @defgroup l2_modif_changori Changing orientation of elements
76 ## @defgroup l2_modif_cutquadr Cutting elements
77 ## @defgroup l2_modif_smooth Smoothing
78 ## @defgroup l2_modif_extrurev Extrusion and Revolution
79 ## @defgroup l2_modif_patterns Pattern mapping
80 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
83 ## @defgroup l1_measurements Measurements
86 from salome.geom import geomBuilder
88 import SMESH # This is necessary for back compatibility
90 from salome.smesh.smesh_algorithm import Mesh_Algorithm
97 def __instancecheck__(cls, inst):
98 """Implement isinstance(inst, cls)."""
99 return any(cls.__subclasscheck__(c)
100 for c in {type(inst), inst.__class__})
102 def __subclasscheck__(cls, sub):
103 """Implement issubclass(sub, cls)."""
104 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
106 ## @addtogroup l1_auxiliary
109 ## Converts an angle from degrees to radians
110 def DegreesToRadians(AngleInDegrees):
112 return AngleInDegrees * pi / 180.0
114 import salome_notebook
115 notebook = salome_notebook.notebook
116 # Salome notebook variable separator
119 ## Return list of variable values from salome notebook.
120 # The last argument, if is callable, is used to modify values got from notebook
121 def ParseParameters(*args):
126 if args and callable( args[-1] ):
127 args, varModifFun = args[:-1], args[-1]
128 for parameter in args:
130 Parameters += str(parameter) + var_separator
132 if isinstance(parameter,str):
133 # check if there is an inexistent variable name
134 if not notebook.isVariable(parameter):
135 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
136 parameter = notebook.get(parameter)
139 parameter = varModifFun(parameter)
142 Result.append(parameter)
145 Parameters = Parameters[:-1]
146 Result.append( Parameters )
147 Result.append( hasVariables )
150 # Parse parameters converting variables to radians
151 def ParseAngles(*args):
152 return ParseParameters( *( args + (DegreesToRadians, )))
154 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
155 # Parameters are stored in PointStruct.parameters attribute
156 def __initPointStruct(point,*args):
157 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
159 SMESH.PointStruct.__init__ = __initPointStruct
161 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
162 # Parameters are stored in AxisStruct.parameters attribute
163 def __initAxisStruct(ax,*args):
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 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
173 if abs(val1 - val2) < tol:
183 if isinstance(obj, SALOMEDS._objref_SObject):
187 ior = salome.orb.object_to_string(obj)
192 studies = salome.myStudyManager.GetOpenStudies()
193 for sname in studies:
194 s = salome.myStudyManager.GetStudyByName(sname)
196 sobj = s.FindObjectIOR(ior)
197 if not sobj: continue
198 return sobj.GetName()
199 if hasattr(obj, "GetName"):
200 # unknown CORBA object, having GetName() method
203 # unknown CORBA object, no GetName() method
206 if hasattr(obj, "GetName"):
207 # unknown non-CORBA object, having GetName() method
210 raise RuntimeError, "Null or invalid object"
212 ## Prints error message if a hypothesis was not assigned.
213 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
215 hypType = "algorithm"
217 hypType = "hypothesis"
220 if hasattr( status, "__getitem__" ):
221 status,reason = status[0],status[1]
222 if status == HYP_UNKNOWN_FATAL :
223 reason = "for unknown reason"
224 elif status == HYP_INCOMPATIBLE :
225 reason = "this hypothesis mismatches the algorithm"
226 elif status == HYP_NOTCONFORM :
227 reason = "a non-conform mesh would be built"
228 elif status == HYP_ALREADY_EXIST :
229 if isAlgo: return # it does not influence anything
230 reason = hypType + " of the same dimension is already assigned to this shape"
231 elif status == HYP_BAD_DIM :
232 reason = hypType + " mismatches the shape"
233 elif status == HYP_CONCURENT :
234 reason = "there are concurrent hypotheses on sub-shapes"
235 elif status == HYP_BAD_SUBSHAPE :
236 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
237 elif status == HYP_BAD_GEOMETRY:
238 reason = "geometry mismatches the expectation of the algorithm"
239 elif status == HYP_HIDDEN_ALGO:
240 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
241 elif status == HYP_HIDING_ALGO:
242 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
243 elif status == HYP_NEED_SHAPE:
244 reason = "algorithm can't work without shape"
245 elif status == HYP_INCOMPAT_HYPS:
251 where = '"%s"' % geomName
253 meshName = GetName( mesh )
254 if meshName and meshName != NO_NAME:
255 where = '"%s" in "%s"' % ( geomName, meshName )
256 if status < HYP_UNKNOWN_FATAL and where:
257 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
259 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
261 print '"%s" was not assigned : %s' %( hypName, reason )
264 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
265 def AssureGeomPublished(mesh, geom, name=''):
266 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
268 if not geom.GetStudyEntry() and \
269 mesh.smeshpyD.GetCurrentStudy():
271 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
272 if studyID != mesh.geompyD.myStudyId:
273 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
275 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
276 # for all groups SubShapeName() returns "Compound_-1"
277 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
279 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
281 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
284 ## Return the first vertex of a geometrical edge by ignoring orientation
285 def FirstVertexOnCurve(mesh, edge):
286 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
288 raise TypeError, "Given object has no vertices"
289 if len( vv ) == 1: return vv[0]
290 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
291 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
292 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
293 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
296 dist1 += abs( xyz[i] - xyz1[i] )
297 dist2 += abs( xyz[i] - xyz2[i] )
303 # end of l1_auxiliary
307 # Warning: smeshInst is a singleton
313 ## This class allows to create, load or manipulate meshes
314 # It has a set of methods to create load or copy meshes, to combine several meshes.
315 # It also has methods to get infos on meshes.
316 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
318 # MirrorType enumeration
319 POINT = SMESH_MeshEditor.POINT
320 AXIS = SMESH_MeshEditor.AXIS
321 PLANE = SMESH_MeshEditor.PLANE
323 # Smooth_Method enumeration
324 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
325 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
327 PrecisionConfusion = smeshPrecisionConfusion
329 # TopAbs_State enumeration
330 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
332 # Methods of splitting a hexahedron into tetrahedra
333 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
339 #print "==== __new__", engine, smeshInst, doLcc
341 if smeshInst is None:
342 # smesh engine is either retrieved from engine, or created
344 # Following test avoids a recursive loop
346 if smeshInst is not None:
347 # smesh engine not created: existing engine found
351 # FindOrLoadComponent called:
352 # 1. CORBA resolution of server
353 # 2. the __new__ method is called again
354 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
355 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
357 # FindOrLoadComponent not called
358 if smeshInst is None:
359 # smeshBuilder instance is created from lcc.FindOrLoadComponent
360 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
361 smeshInst = super(smeshBuilder,cls).__new__(cls)
363 # smesh engine not created: existing engine found
364 #print "==== existing ", engine, smeshInst, doLcc
366 #print "====1 ", smeshInst
369 #print "====2 ", smeshInst
374 #print "--------------- smeshbuilder __init__ ---", created
377 SMESH._objref_SMESH_Gen.__init__(self)
379 ## Dump component to the Python script
380 # This method overrides IDL function to allow default values for the parameters.
381 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
382 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
384 ## Set mode of DumpPython(), \a historical or \a snapshot.
385 # In the \a historical mode, the Python Dump script includes all commands
386 # performed by SMESH engine. In the \a snapshot mode, commands
387 # relating to objects removed from the Study are excluded from the script
388 # as well as commands not influencing the current state of meshes
389 def SetDumpPythonHistorical(self, isHistorical):
390 if isHistorical: val = "true"
392 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
394 ## Sets the current study and Geometry component
395 # @ingroup l1_auxiliary
396 def init_smesh(self,theStudy,geompyD = None):
398 self.SetCurrentStudy(theStudy,geompyD)
401 notebook.myStudy = theStudy
403 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
404 # or a mesh wrapping a CORBA mesh given as a parameter.
405 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
406 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
407 # (2) a Geometrical object for meshing or
409 # @param name the name for the new mesh.
410 # @return an instance of Mesh class.
411 # @ingroup l2_construct
412 def Mesh(self, obj=0, name=0):
413 if isinstance(obj,str):
415 return Mesh(self,self.geompyD,obj,name)
417 ## Returns a long value from enumeration
418 # @ingroup l1_controls
419 def EnumToLong(self,theItem):
422 ## Returns a string representation of the color.
423 # To be used with filters.
424 # @param c color value (SALOMEDS.Color)
425 # @ingroup l1_controls
426 def ColorToString(self,c):
428 if isinstance(c, SALOMEDS.Color):
429 val = "%s;%s;%s" % (c.R, c.G, c.B)
430 elif isinstance(c, str):
433 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
436 ## Gets PointStruct from vertex
437 # @param theVertex a GEOM object(vertex)
438 # @return SMESH.PointStruct
439 # @ingroup l1_auxiliary
440 def GetPointStruct(self,theVertex):
441 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
442 return PointStruct(x,y,z)
444 ## Gets DirStruct from vector
445 # @param theVector a GEOM object(vector)
446 # @return SMESH.DirStruct
447 # @ingroup l1_auxiliary
448 def GetDirStruct(self,theVector):
449 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
450 if(len(vertices) != 2):
451 print "Error: vector object is incorrect."
453 p1 = self.geompyD.PointCoordinates(vertices[0])
454 p2 = self.geompyD.PointCoordinates(vertices[1])
455 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
456 dirst = DirStruct(pnt)
459 ## Makes DirStruct from a triplet
460 # @param x,y,z vector components
461 # @return SMESH.DirStruct
462 # @ingroup l1_auxiliary
463 def MakeDirStruct(self,x,y,z):
464 pnt = PointStruct(x,y,z)
465 return DirStruct(pnt)
467 ## Get AxisStruct from object
468 # @param theObj a GEOM object (line or plane)
469 # @return SMESH.AxisStruct
470 # @ingroup l1_auxiliary
471 def GetAxisStruct(self,theObj):
473 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
476 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
477 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
478 vertex1 = self.geompyD.PointCoordinates(vertex1)
479 vertex2 = self.geompyD.PointCoordinates(vertex2)
480 vertex3 = self.geompyD.PointCoordinates(vertex3)
481 vertex4 = self.geompyD.PointCoordinates(vertex4)
482 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
483 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
484 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] ]
485 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
486 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
487 elif len(edges) == 1:
488 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
489 p1 = self.geompyD.PointCoordinates( vertex1 )
490 p2 = self.geompyD.PointCoordinates( vertex2 )
491 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
492 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
493 elif theObj.GetShapeType() == GEOM.VERTEX:
494 x,y,z = self.geompyD.PointCoordinates( theObj )
495 axis = AxisStruct( x,y,z, 1,0,0,)
496 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
499 # From SMESH_Gen interface:
500 # ------------------------
502 ## Sets the given name to the object
503 # @param obj the object to rename
504 # @param name a new object name
505 # @ingroup l1_auxiliary
506 def SetName(self, obj, name):
507 if isinstance( obj, Mesh ):
509 elif isinstance( obj, Mesh_Algorithm ):
510 obj = obj.GetAlgorithm()
511 ior = salome.orb.object_to_string(obj)
512 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
514 ## Sets the current mode
515 # @ingroup l1_auxiliary
516 def SetEmbeddedMode( self,theMode ):
517 #self.SetEmbeddedMode(theMode)
518 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
520 ## Gets the current mode
521 # @ingroup l1_auxiliary
522 def IsEmbeddedMode(self):
523 #return self.IsEmbeddedMode()
524 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
526 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
527 # switch OFF automatic pubilishing in the Study of mesh objects.
528 # @ingroup l1_auxiliary
529 def SetCurrentStudy( self, theStudy, geompyD = None ):
530 #self.SetCurrentStudy(theStudy)
532 from salome.geom import geomBuilder
533 geompyD = geomBuilder.geom
536 self.SetGeomEngine(geompyD)
537 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
540 notebook = salome_notebook.NoteBook( theStudy )
542 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
544 sb = theStudy.NewBuilder()
545 sc = theStudy.FindComponent("SMESH")
546 if sc: sb.LoadWith(sc, self)
550 ## Gets the current study
551 # @ingroup l1_auxiliary
552 def GetCurrentStudy(self):
553 #return self.GetCurrentStudy()
554 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
556 ## Creates a Mesh object importing data from the given UNV file
557 # @return an instance of Mesh class
559 def CreateMeshesFromUNV( self,theFileName ):
560 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
561 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
564 ## Creates a Mesh object(s) importing data from the given MED file
565 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
567 def CreateMeshesFromMED( self,theFileName ):
568 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
569 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
570 return aMeshes, aStatus
572 ## Creates a Mesh object(s) importing data from the given SAUV file
573 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
575 def CreateMeshesFromSAUV( self,theFileName ):
576 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
577 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
578 return aMeshes, aStatus
580 ## Creates a Mesh object importing data from the given STL file
581 # @return an instance of Mesh class
583 def CreateMeshesFromSTL( self, theFileName ):
584 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
585 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
588 ## Creates Mesh objects importing data from the given CGNS file
589 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
591 def CreateMeshesFromCGNS( self, theFileName ):
592 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
593 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
594 return aMeshes, aStatus
596 ## Creates a Mesh object importing data from the given GMF file.
597 # GMF files must have .mesh extension for the ASCII format and .meshb for
599 # @return [ an instance of Mesh class, SMESH.ComputeError ]
601 def CreateMeshesFromGMF( self, theFileName ):
602 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
605 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
606 return Mesh(self, self.geompyD, aSmeshMesh), error
608 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
609 # present in the new mesh.
610 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
611 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
612 # @param mergeNodesAndElements if true, equal nodes and elements are merged
613 # @param mergeTolerance tolerance for merging nodes
614 # @param allGroups forces creation of groups corresponding to every input mesh
615 # @param name name of a new mesh
616 # @return an instance of Mesh class
617 def Concatenate( self, meshes, uniteIdenticalGroups,
618 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
620 if not meshes: return None
621 for i,m in enumerate(meshes):
622 if isinstance(m, Mesh):
623 meshes[i] = m.GetMesh()
624 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
625 meshes[0].SetParameters(Parameters)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
630 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
631 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
632 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
635 ## Create a mesh by copying a part of another mesh.
636 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
637 # to copy nodes or elements not contained in any mesh object,
638 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
639 # @param meshName a name of the new mesh
640 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
641 # @param toKeepIDs to preserve order of the copied elements or not
642 # @return an instance of Mesh class
643 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
644 if (isinstance( meshPart, Mesh )):
645 meshPart = meshPart.GetMesh()
646 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
647 return Mesh(self, self.geompyD, mesh)
649 ## From SMESH_Gen interface
650 # @return the list of integer values
651 # @ingroup l1_auxiliary
652 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
653 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
655 ## From SMESH_Gen interface. Creates a pattern
656 # @return an instance of SMESH_Pattern
658 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
659 # @ingroup l2_modif_patterns
660 def GetPattern(self):
661 return SMESH._objref_SMESH_Gen.GetPattern(self)
663 ## Sets number of segments per diagonal of boundary box of geometry by which
664 # default segment length of appropriate 1D hypotheses is defined.
665 # Default value is 10
666 # @ingroup l1_auxiliary
667 def SetBoundaryBoxSegmentation(self, nbSegments):
668 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
670 # Filtering. Auxiliary functions:
671 # ------------------------------
673 ## Creates an empty criterion
674 # @return SMESH.Filter.Criterion
675 # @ingroup l1_controls
676 def GetEmptyCriterion(self):
677 Type = self.EnumToLong(FT_Undefined)
678 Compare = self.EnumToLong(FT_Undefined)
682 UnaryOp = self.EnumToLong(FT_Undefined)
683 BinaryOp = self.EnumToLong(FT_Undefined)
686 Precision = -1 ##@1e-07
687 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
688 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
690 ## Creates a criterion by the given parameters
691 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
692 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
693 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
694 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
695 # @param Threshold the threshold value (range of ids as string, shape, numeric)
696 # @param UnaryOp FT_LogicalNOT or FT_Undefined
697 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
698 # FT_Undefined (must be for the last criterion of all criteria)
699 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
700 # FT_LyingOnGeom, FT_CoplanarFaces criteria
701 # @return SMESH.Filter.Criterion
703 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
704 # @ingroup l1_controls
705 def GetCriterion(self,elementType,
707 Compare = FT_EqualTo,
709 UnaryOp=FT_Undefined,
710 BinaryOp=FT_Undefined,
712 if not CritType in SMESH.FunctorType._items:
713 raise TypeError, "CritType should be of SMESH.FunctorType"
714 aCriterion = self.GetEmptyCriterion()
715 aCriterion.TypeOfElement = elementType
716 aCriterion.Type = self.EnumToLong(CritType)
717 aCriterion.Tolerance = Tolerance
719 aThreshold = Threshold
721 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
722 aCriterion.Compare = self.EnumToLong(Compare)
723 elif Compare == "=" or Compare == "==":
724 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
726 aCriterion.Compare = self.EnumToLong(FT_LessThan)
728 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
729 elif Compare != FT_Undefined:
730 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
733 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
734 FT_BelongToCylinder, FT_LyingOnGeom]:
735 # Checks that Threshold is GEOM object
736 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
737 aCriterion.ThresholdStr = GetName(aThreshold)
738 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
739 if not aCriterion.ThresholdID:
740 name = aCriterion.ThresholdStr
742 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
743 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
744 # or a name of GEOM object
745 elif isinstance( aThreshold, str ):
746 aCriterion.ThresholdStr = aThreshold
748 print "Error: The Threshold should be a shape."
750 if isinstance(UnaryOp,float):
751 aCriterion.Tolerance = UnaryOp
752 UnaryOp = FT_Undefined
754 elif CritType == FT_RangeOfIds:
755 # Checks that Threshold is string
756 if isinstance(aThreshold, str):
757 aCriterion.ThresholdStr = aThreshold
759 print "Error: The Threshold should be a string."
761 elif CritType == FT_CoplanarFaces:
762 # Checks the Threshold
763 if isinstance(aThreshold, int):
764 aCriterion.ThresholdID = str(aThreshold)
765 elif isinstance(aThreshold, str):
768 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
769 aCriterion.ThresholdID = aThreshold
772 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
773 elif CritType == FT_ConnectedElements:
774 # Checks the Threshold
775 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
776 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
777 if not aCriterion.ThresholdID:
778 name = aThreshold.GetName()
780 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
781 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
782 elif isinstance(aThreshold, int): # node id
783 aCriterion.Threshold = aThreshold
784 elif isinstance(aThreshold, list): # 3 point coordinates
785 if len( aThreshold ) < 3:
786 raise ValueError, "too few point coordinates, must be 3"
787 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
788 elif isinstance(aThreshold, str):
789 if aThreshold.isdigit():
790 aCriterion.Threshold = aThreshold # node id
792 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
795 "The Threshold should either a VERTEX, or a node ID, "\
796 "or a list of point coordinates and not '%s'"%aThreshold
797 elif CritType == FT_ElemGeomType:
798 # Checks the Threshold
800 aCriterion.Threshold = self.EnumToLong(aThreshold)
801 assert( aThreshold in SMESH.GeometryType._items )
803 if isinstance(aThreshold, int):
804 aCriterion.Threshold = aThreshold
806 print "Error: The Threshold should be an integer or SMESH.GeometryType."
810 elif CritType == FT_EntityType:
811 # Checks the Threshold
813 aCriterion.Threshold = self.EnumToLong(aThreshold)
814 assert( aThreshold in SMESH.EntityType._items )
816 if isinstance(aThreshold, int):
817 aCriterion.Threshold = aThreshold
819 print "Error: The Threshold should be an integer or SMESH.EntityType."
824 elif CritType == FT_GroupColor:
825 # Checks the Threshold
827 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
829 print "Error: The threshold value should be of SALOMEDS.Color type"
832 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
833 FT_LinearOrQuadratic, FT_BadOrientedVolume,
834 FT_BareBorderFace, FT_BareBorderVolume,
835 FT_OverConstrainedFace, FT_OverConstrainedVolume,
836 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
837 # At this point the Threshold is unnecessary
838 if aThreshold == FT_LogicalNOT:
839 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
840 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
841 aCriterion.BinaryOp = aThreshold
845 aThreshold = float(aThreshold)
846 aCriterion.Threshold = aThreshold
848 print "Error: The Threshold should be a number."
851 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
852 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
854 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
855 aCriterion.BinaryOp = self.EnumToLong(Threshold)
857 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
858 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
860 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
861 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
865 ## Creates a filter with the given parameters
866 # @param elementType the type of elements in the group
867 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
868 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
869 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
870 # @param UnaryOp FT_LogicalNOT or FT_Undefined
871 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
872 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
873 # @param mesh the mesh to initialize the filter with
874 # @return SMESH_Filter
876 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
877 # @ingroup l1_controls
878 def GetFilter(self,elementType,
879 CritType=FT_Undefined,
882 UnaryOp=FT_Undefined,
885 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
886 aFilterMgr = self.CreateFilterManager()
887 aFilter = aFilterMgr.CreateFilter()
889 aCriteria.append(aCriterion)
890 aFilter.SetCriteria(aCriteria)
892 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
893 else : aFilter.SetMesh( mesh )
894 aFilterMgr.UnRegister()
897 ## Creates a filter from criteria
898 # @param criteria a list of criteria
899 # @param binOp binary operator used when binary operator of criteria is undefined
900 # @return SMESH_Filter
902 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
903 # @ingroup l1_controls
904 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
905 for i in range( len( criteria ) - 1 ):
906 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
907 criteria[i].BinaryOp = self.EnumToLong( binOp )
908 aFilterMgr = self.CreateFilterManager()
909 aFilter = aFilterMgr.CreateFilter()
910 aFilter.SetCriteria(criteria)
911 aFilterMgr.UnRegister()
914 ## Creates a numerical functor by its type
915 # @param theCriterion FT_...; functor type
916 # @return SMESH_NumericalFunctor
917 # @ingroup l1_controls
918 def GetFunctor(self,theCriterion):
919 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
921 aFilterMgr = self.CreateFilterManager()
923 if theCriterion == FT_AspectRatio:
924 functor = aFilterMgr.CreateAspectRatio()
925 elif theCriterion == FT_AspectRatio3D:
926 functor = aFilterMgr.CreateAspectRatio3D()
927 elif theCriterion == FT_Warping:
928 functor = aFilterMgr.CreateWarping()
929 elif theCriterion == FT_MinimumAngle:
930 functor = aFilterMgr.CreateMinimumAngle()
931 elif theCriterion == FT_Taper:
932 functor = aFilterMgr.CreateTaper()
933 elif theCriterion == FT_Skew:
934 functor = aFilterMgr.CreateSkew()
935 elif theCriterion == FT_Area:
936 functor = aFilterMgr.CreateArea()
937 elif theCriterion == FT_Volume3D:
938 functor = aFilterMgr.CreateVolume3D()
939 elif theCriterion == FT_MaxElementLength2D:
940 functor = aFilterMgr.CreateMaxElementLength2D()
941 elif theCriterion == FT_MaxElementLength3D:
942 functor = aFilterMgr.CreateMaxElementLength3D()
943 elif theCriterion == FT_MultiConnection:
944 functor = aFilterMgr.CreateMultiConnection()
945 elif theCriterion == FT_MultiConnection2D:
946 functor = aFilterMgr.CreateMultiConnection2D()
947 elif theCriterion == FT_Length:
948 functor = aFilterMgr.CreateLength()
949 elif theCriterion == FT_Length2D:
950 functor = aFilterMgr.CreateLength2D()
952 print "Error: given parameter is not numerical functor type."
953 aFilterMgr.UnRegister()
956 ## Creates hypothesis
957 # @param theHType mesh hypothesis type (string)
958 # @param theLibName mesh plug-in library name
959 # @return created hypothesis instance
960 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
961 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
963 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
966 # wrap hypothesis methods
967 #print "HYPOTHESIS", theHType
968 for meth_name in dir( hyp.__class__ ):
969 if not meth_name.startswith("Get") and \
970 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
971 method = getattr ( hyp.__class__, meth_name )
973 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
977 ## Gets the mesh statistic
978 # @return dictionary "element type" - "count of elements"
979 # @ingroup l1_meshinfo
980 def GetMeshInfo(self, obj):
981 if isinstance( obj, Mesh ):
984 if hasattr(obj, "GetMeshInfo"):
985 values = obj.GetMeshInfo()
986 for i in range(SMESH.Entity_Last._v):
987 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
991 ## Get minimum distance between two objects
993 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
994 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
996 # @param src1 first source object
997 # @param src2 second source object
998 # @param id1 node/element id from the first source
999 # @param id2 node/element id from the second (or first) source
1000 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1001 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1002 # @return minimum distance value
1003 # @sa GetMinDistance()
1004 # @ingroup l1_measurements
1005 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1006 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1010 result = result.value
1013 ## Get measure structure specifying minimum distance data between two objects
1015 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1016 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1018 # @param src1 first source object
1019 # @param src2 second source object
1020 # @param id1 node/element id from the first source
1021 # @param id2 node/element id from the second (or first) source
1022 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1023 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1024 # @return Measure structure or None if input data is invalid
1026 # @ingroup l1_measurements
1027 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1028 if isinstance(src1, Mesh): src1 = src1.mesh
1029 if isinstance(src2, Mesh): src2 = src2.mesh
1030 if src2 is None and id2 != 0: src2 = src1
1031 if not hasattr(src1, "_narrow"): return None
1032 src1 = src1._narrow(SMESH.SMESH_IDSource)
1033 if not src1: return None
1034 unRegister = genObjUnRegister()
1037 e = m.GetMeshEditor()
1039 src1 = e.MakeIDSource([id1], SMESH.FACE)
1041 src1 = e.MakeIDSource([id1], SMESH.NODE)
1042 unRegister.set( src1 )
1044 if hasattr(src2, "_narrow"):
1045 src2 = src2._narrow(SMESH.SMESH_IDSource)
1046 if src2 and id2 != 0:
1048 e = m.GetMeshEditor()
1050 src2 = e.MakeIDSource([id2], SMESH.FACE)
1052 src2 = e.MakeIDSource([id2], SMESH.NODE)
1053 unRegister.set( src2 )
1056 aMeasurements = self.CreateMeasurements()
1057 unRegister.set( aMeasurements )
1058 result = aMeasurements.MinDistance(src1, src2)
1061 ## Get bounding box of the specified object(s)
1062 # @param objects single source object or list of source objects
1063 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1064 # @sa GetBoundingBox()
1065 # @ingroup l1_measurements
1066 def BoundingBox(self, objects):
1067 result = self.GetBoundingBox(objects)
1071 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1074 ## Get measure structure specifying bounding box data of the specified object(s)
1075 # @param objects single source object or list of source objects
1076 # @return Measure structure
1078 # @ingroup l1_measurements
1079 def GetBoundingBox(self, objects):
1080 if isinstance(objects, tuple):
1081 objects = list(objects)
1082 if not isinstance(objects, list):
1086 if isinstance(o, Mesh):
1087 srclist.append(o.mesh)
1088 elif hasattr(o, "_narrow"):
1089 src = o._narrow(SMESH.SMESH_IDSource)
1090 if src: srclist.append(src)
1093 aMeasurements = self.CreateMeasurements()
1094 result = aMeasurements.BoundingBox(srclist)
1095 aMeasurements.UnRegister()
1098 ## Get sum of lengths of all 1D elements in the mesh object.
1099 # @param obj mesh, submesh or group
1100 # @return sum of lengths of all 1D elements
1101 # @ingroup l1_measurements
1102 def GetLength(self, obj):
1103 if isinstance(obj, Mesh): obj = obj.mesh
1104 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1105 aMeasurements = self.CreateMeasurements()
1106 value = aMeasurements.Length(obj)
1107 aMeasurements.UnRegister()
1110 ## Get sum of areas of all 2D elements in the mesh object.
1111 # @param obj mesh, submesh or group
1112 # @return sum of areas of all 2D elements
1113 # @ingroup l1_measurements
1114 def GetArea(self, obj):
1115 if isinstance(obj, Mesh): obj = obj.mesh
1116 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1117 aMeasurements = self.CreateMeasurements()
1118 value = aMeasurements.Area(obj)
1119 aMeasurements.UnRegister()
1122 ## Get sum of volumes of all 3D elements in the mesh object.
1123 # @param obj mesh, submesh or group
1124 # @return sum of volumes of all 3D elements
1125 # @ingroup l1_measurements
1126 def GetVolume(self, obj):
1127 if isinstance(obj, Mesh): obj = obj.mesh
1128 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1129 aMeasurements = self.CreateMeasurements()
1130 value = aMeasurements.Volume(obj)
1131 aMeasurements.UnRegister()
1134 pass # end of class smeshBuilder
1137 #Registering the new proxy for SMESH_Gen
1138 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1140 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1141 # interface to create or load meshes.
1146 # salome.salome_init()
1147 # from salome.smesh import smeshBuilder
1148 # smesh = smeshBuilder.New(theStudy)
1150 # @param study SALOME study, generally obtained by salome.myStudy.
1151 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1152 # @return smeshBuilder instance
1154 def New( study, instance=None):
1156 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1157 interface to create or load meshes.
1161 salome.salome_init()
1162 from salome.smesh import smeshBuilder
1163 smesh = smeshBuilder.New(theStudy)
1166 study SALOME study, generally obtained by salome.myStudy.
1167 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1169 smeshBuilder instance
1177 smeshInst = smeshBuilder()
1178 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1179 smeshInst.init_smesh(study)
1183 # Public class: Mesh
1184 # ==================
1186 ## This class allows defining and managing a mesh.
1187 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1188 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1189 # new nodes and elements and by changing the existing entities), to get information
1190 # about a mesh and to export a mesh into different formats.
1192 __metaclass__ = MeshMeta
1200 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1201 # sets the GUI name of this mesh to \a name.
1202 # @param smeshpyD an instance of smeshBuilder class
1203 # @param geompyD an instance of geomBuilder class
1204 # @param obj Shape to be meshed or SMESH_Mesh object
1205 # @param name Study name of the mesh
1206 # @ingroup l2_construct
1207 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1208 self.smeshpyD=smeshpyD
1209 self.geompyD=geompyD
1214 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1217 # publish geom of mesh (issue 0021122)
1218 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1220 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1221 if studyID != geompyD.myStudyId:
1222 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1225 geo_name = name + " shape"
1227 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1228 geompyD.addToStudy( self.geom, geo_name )
1229 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1231 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1234 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1236 self.smeshpyD.SetName(self.mesh, name)
1238 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1241 self.geom = self.mesh.GetShapeToMesh()
1243 self.editor = self.mesh.GetMeshEditor()
1244 self.functors = [None] * SMESH.FT_Undefined._v
1246 # set self to algoCreator's
1247 for attrName in dir(self):
1248 attr = getattr( self, attrName )
1249 if isinstance( attr, algoCreator ):
1250 #print "algoCreator ", attrName
1251 setattr( self, attrName, attr.copy( self ))
1256 ## Destructor. Clean-up resources
1259 #self.mesh.UnRegister()
1263 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1264 # @param theMesh a SMESH_Mesh object
1265 # @ingroup l2_construct
1266 def SetMesh(self, theMesh):
1267 # do not call Register() as this prevents mesh servant deletion at closing study
1268 #if self.mesh: self.mesh.UnRegister()
1271 #self.mesh.Register()
1272 self.geom = self.mesh.GetShapeToMesh()
1275 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1276 # @return a SMESH_Mesh object
1277 # @ingroup l2_construct
1281 ## Gets the name of the mesh
1282 # @return the name of the mesh as a string
1283 # @ingroup l2_construct
1285 name = GetName(self.GetMesh())
1288 ## Sets a name to the mesh
1289 # @param name a new name of the mesh
1290 # @ingroup l2_construct
1291 def SetName(self, name):
1292 self.smeshpyD.SetName(self.GetMesh(), name)
1294 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1295 # The subMesh object gives access to the IDs of nodes and elements.
1296 # @param geom a geometrical object (shape)
1297 # @param name a name for the submesh
1298 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1299 # @ingroup l2_submeshes
1300 def GetSubMesh(self, geom, name):
1301 AssureGeomPublished( self, geom, name )
1302 submesh = self.mesh.GetSubMesh( geom, name )
1305 ## Returns the shape associated to the mesh
1306 # @return a GEOM_Object
1307 # @ingroup l2_construct
1311 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1312 # @param geom the shape to be meshed (GEOM_Object)
1313 # @ingroup l2_construct
1314 def SetShape(self, geom):
1315 self.mesh = self.smeshpyD.CreateMesh(geom)
1317 ## Loads mesh from the study after opening the study
1321 ## Returns true if the hypotheses are defined well
1322 # @param theSubObject a sub-shape of a mesh shape
1323 # @return True or False
1324 # @ingroup l2_construct
1325 def IsReadyToCompute(self, theSubObject):
1326 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1328 ## Returns errors of hypotheses definition.
1329 # The list of errors is empty if everything is OK.
1330 # @param theSubObject a sub-shape of a mesh shape
1331 # @return a list of errors
1332 # @ingroup l2_construct
1333 def GetAlgoState(self, theSubObject):
1334 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1336 ## Returns a geometrical object on which the given element was built.
1337 # The returned geometrical object, if not nil, is either found in the
1338 # study or published by this method with the given name
1339 # @param theElementID the id of the mesh element
1340 # @param theGeomName the user-defined name of the geometrical object
1341 # @return GEOM::GEOM_Object instance
1342 # @ingroup l2_construct
1343 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1344 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1346 ## Returns the mesh dimension depending on the dimension of the underlying shape
1347 # or, if the mesh is not based on any shape, basing on deimension of elements
1348 # @return mesh dimension as an integer value [0,3]
1349 # @ingroup l1_auxiliary
1350 def MeshDimension(self):
1351 if self.mesh.HasShapeToMesh():
1352 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1353 if len( shells ) > 0 :
1355 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1357 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1362 if self.NbVolumes() > 0: return 3
1363 if self.NbFaces() > 0: return 2
1364 if self.NbEdges() > 0: return 1
1367 ## Evaluates size of prospective mesh on a shape
1368 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1369 # To know predicted number of e.g. edges, inquire it this way
1370 # Evaluate()[ EnumToLong( Entity_Edge )]
1371 def Evaluate(self, geom=0):
1372 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1374 geom = self.mesh.GetShapeToMesh()
1377 return self.smeshpyD.Evaluate(self.mesh, geom)
1380 ## Computes the mesh and returns the status of the computation
1381 # @param geom geomtrical shape on which mesh data should be computed
1382 # @param discardModifs if True and the mesh has been edited since
1383 # a last total re-compute and that may prevent successful partial re-compute,
1384 # then the mesh is cleaned before Compute()
1385 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1386 # @return True or False
1387 # @ingroup l2_construct
1388 def Compute(self, geom=0, discardModifs=False, refresh=False):
1389 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1391 geom = self.mesh.GetShapeToMesh()
1396 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1398 ok = self.smeshpyD.Compute(self.mesh, geom)
1399 except SALOME.SALOME_Exception, ex:
1400 print "Mesh computation failed, exception caught:"
1401 print " ", ex.details.text
1404 print "Mesh computation failed, exception caught:"
1405 traceback.print_exc()
1409 # Treat compute errors
1410 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1411 for err in computeErrors:
1413 if self.mesh.HasShapeToMesh():
1415 mainIOR = salome.orb.object_to_string(geom)
1416 for sname in salome.myStudyManager.GetOpenStudies():
1417 s = salome.myStudyManager.GetStudyByName(sname)
1419 mainSO = s.FindObjectIOR(mainIOR)
1420 if not mainSO: continue
1421 if err.subShapeID == 1:
1422 shapeText = ' on "%s"' % mainSO.GetName()
1423 subIt = s.NewChildIterator(mainSO)
1425 subSO = subIt.Value()
1427 obj = subSO.GetObject()
1428 if not obj: continue
1429 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1431 ids = go.GetSubShapeIndices()
1432 if len(ids) == 1 and ids[0] == err.subShapeID:
1433 shapeText = ' on "%s"' % subSO.GetName()
1436 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1438 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1440 shapeText = " on subshape #%s" % (err.subShapeID)
1442 shapeText = " on subshape #%s" % (err.subShapeID)
1444 stdErrors = ["OK", #COMPERR_OK
1445 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1446 "std::exception", #COMPERR_STD_EXCEPTION
1447 "OCC exception", #COMPERR_OCC_EXCEPTION
1448 "..", #COMPERR_SLM_EXCEPTION
1449 "Unknown exception", #COMPERR_EXCEPTION
1450 "Memory allocation problem", #COMPERR_MEMORY_PB
1451 "Algorithm failed", #COMPERR_ALGO_FAILED
1452 "Unexpected geometry", #COMPERR_BAD_SHAPE
1453 "Warning", #COMPERR_WARNING
1454 "Computation cancelled",#COMPERR_CANCELED
1455 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1457 if err.code < len(stdErrors): errText = stdErrors[err.code]
1459 errText = "code %s" % -err.code
1460 if errText: errText += ". "
1461 errText += err.comment
1462 if allReasons != "":allReasons += "\n"
1464 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1466 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1470 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1472 if err.isGlobalAlgo:
1480 reason = '%s %sD algorithm is missing' % (glob, dim)
1481 elif err.state == HYP_MISSING:
1482 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1483 % (glob, dim, name, dim))
1484 elif err.state == HYP_NOTCONFORM:
1485 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1486 elif err.state == HYP_BAD_PARAMETER:
1487 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1488 % ( glob, dim, name ))
1489 elif err.state == HYP_BAD_GEOMETRY:
1490 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1491 'geometry' % ( glob, dim, name ))
1492 elif err.state == HYP_HIDDEN_ALGO:
1493 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1494 'algorithm of upper dimension generating %sD mesh'
1495 % ( glob, dim, name, glob, dim ))
1497 reason = ("For unknown reason. "
1498 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1500 if allReasons != "":allReasons += "\n"
1501 allReasons += "- " + reason
1503 if not ok or allReasons != "":
1504 msg = '"' + GetName(self.mesh) + '"'
1505 if ok: msg += " has been computed with warnings"
1506 else: msg += " has not been computed"
1507 if allReasons != "": msg += ":"
1512 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1513 smeshgui = salome.ImportComponentGUI("SMESH")
1514 smeshgui.Init(self.mesh.GetStudyId())
1515 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1516 if refresh: salome.sg.updateObjBrowser(1)
1520 ## Return submesh objects list in meshing order
1521 # @return list of list of submesh objects
1522 # @ingroup l2_construct
1523 def GetMeshOrder(self):
1524 return self.mesh.GetMeshOrder()
1526 ## Return submesh objects list in meshing order
1527 # @return list of list of submesh objects
1528 # @ingroup l2_construct
1529 def SetMeshOrder(self, submeshes):
1530 return self.mesh.SetMeshOrder(submeshes)
1532 ## Removes all nodes and elements
1533 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1534 # @ingroup l2_construct
1535 def Clear(self, refresh=False):
1537 if ( salome.sg.hasDesktop() and
1538 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1539 smeshgui = salome.ImportComponentGUI("SMESH")
1540 smeshgui.Init(self.mesh.GetStudyId())
1541 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1542 if refresh: salome.sg.updateObjBrowser(1)
1544 ## Removes all nodes and elements of indicated shape
1545 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1546 # @param geomId the ID of a sub-shape to remove elements on
1547 # @ingroup l2_construct
1548 def ClearSubMesh(self, geomId, refresh=False):
1549 self.mesh.ClearSubMesh(geomId)
1550 if salome.sg.hasDesktop():
1551 smeshgui = salome.ImportComponentGUI("SMESH")
1552 smeshgui.Init(self.mesh.GetStudyId())
1553 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1554 if refresh: salome.sg.updateObjBrowser(1)
1556 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1557 # @param fineness [0.0,1.0] defines mesh fineness
1558 # @return True or False
1559 # @ingroup l3_algos_basic
1560 def AutomaticTetrahedralization(self, fineness=0):
1561 dim = self.MeshDimension()
1563 self.RemoveGlobalHypotheses()
1564 self.Segment().AutomaticLength(fineness)
1566 self.Triangle().LengthFromEdges()
1571 return self.Compute()
1573 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1574 # @param fineness [0.0, 1.0] defines mesh fineness
1575 # @return True or False
1576 # @ingroup l3_algos_basic
1577 def AutomaticHexahedralization(self, fineness=0):
1578 dim = self.MeshDimension()
1579 # assign the hypotheses
1580 self.RemoveGlobalHypotheses()
1581 self.Segment().AutomaticLength(fineness)
1588 return self.Compute()
1590 ## Assigns a hypothesis
1591 # @param hyp a hypothesis to assign
1592 # @param geom a subhape of mesh geometry
1593 # @return SMESH.Hypothesis_Status
1594 # @ingroup l2_hypotheses
1595 def AddHypothesis(self, hyp, geom=0):
1596 if isinstance( hyp, Mesh_Algorithm ):
1597 hyp = hyp.GetAlgorithm()
1602 geom = self.mesh.GetShapeToMesh()
1605 if self.mesh.HasShapeToMesh():
1606 hyp_type = hyp.GetName()
1607 lib_name = hyp.GetLibName()
1608 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1609 if checkAll and geom:
1610 checkAll = geom.GetType() == 37
1611 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1613 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1614 status = self.mesh.AddHypothesis(geom, hyp)
1616 status = HYP_BAD_GEOMETRY,""
1617 hyp_name = GetName( hyp )
1620 geom_name = geom.GetName()
1621 isAlgo = hyp._narrow( SMESH_Algo )
1622 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1625 ## Return True if an algorithm of hypothesis is assigned to a given shape
1626 # @param hyp a hypothesis to check
1627 # @param geom a subhape of mesh geometry
1628 # @return True of False
1629 # @ingroup l2_hypotheses
1630 def IsUsedHypothesis(self, hyp, geom):
1631 if not hyp: # or not geom
1633 if isinstance( hyp, Mesh_Algorithm ):
1634 hyp = hyp.GetAlgorithm()
1636 hyps = self.GetHypothesisList(geom)
1638 if h.GetId() == hyp.GetId():
1642 ## Unassigns a hypothesis
1643 # @param hyp a hypothesis to unassign
1644 # @param geom a sub-shape of mesh geometry
1645 # @return SMESH.Hypothesis_Status
1646 # @ingroup l2_hypotheses
1647 def RemoveHypothesis(self, hyp, geom=0):
1650 if isinstance( hyp, Mesh_Algorithm ):
1651 hyp = hyp.GetAlgorithm()
1657 if self.IsUsedHypothesis( hyp, shape ):
1658 return self.mesh.RemoveHypothesis( shape, hyp )
1659 hypName = GetName( hyp )
1660 geoName = GetName( shape )
1661 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1664 ## Gets the list of hypotheses added on a geometry
1665 # @param geom a sub-shape of mesh geometry
1666 # @return the sequence of SMESH_Hypothesis
1667 # @ingroup l2_hypotheses
1668 def GetHypothesisList(self, geom):
1669 return self.mesh.GetHypothesisList( geom )
1671 ## Removes all global hypotheses
1672 # @ingroup l2_hypotheses
1673 def RemoveGlobalHypotheses(self):
1674 current_hyps = self.mesh.GetHypothesisList( self.geom )
1675 for hyp in current_hyps:
1676 self.mesh.RemoveHypothesis( self.geom, hyp )
1680 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1681 ## allowing to overwrite the file if it exists or add the exported data to its contents
1682 # @param f is the file name
1683 # @param auto_groups boolean parameter for creating/not creating
1684 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1685 # the typical use is auto_groups=false.
1686 # @param version MED format version(MED_V2_1 or MED_V2_2)
1687 # @param overwrite boolean parameter for overwriting/not overwriting the file
1688 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1689 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1690 # - 1D if all mesh nodes lie on OX coordinate axis, or
1691 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1692 # - 3D in the rest cases.
1693 # If @a autoDimension is @c False, the space dimension is always 3.
1694 # @param fields : list of GEOM fields defined on the shape to mesh.
1695 # @param geomAssocFields : each character of this string means a need to export a
1696 # corresponding field; correspondence between fields and characters is following:
1697 # - 'v' stands for _vertices_ field;
1698 # - 'e' stands for _edges_ field;
1699 # - 'f' stands for _faces_ field;
1700 # - 's' stands for _solids_ field.
1701 # @ingroup l2_impexp
1702 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1703 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1704 if meshPart or fields or geomAssocFields:
1705 unRegister = genObjUnRegister()
1706 if isinstance( meshPart, list ):
1707 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1708 unRegister.set( meshPart )
1709 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1710 fields, geomAssocFields)
1712 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1714 ## Exports the mesh in a file in SAUV format
1715 # @param f is the file name
1716 # @param auto_groups boolean parameter for creating/not creating
1717 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1718 # the typical use is auto_groups=false.
1719 # @ingroup l2_impexp
1720 def ExportSAUV(self, f, auto_groups=0):
1721 self.mesh.ExportSAUV(f, auto_groups)
1723 ## Exports the mesh in a file in DAT format
1724 # @param f the file name
1725 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1726 # @ingroup l2_impexp
1727 def ExportDAT(self, f, meshPart=None):
1729 unRegister = genObjUnRegister()
1730 if isinstance( meshPart, list ):
1731 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1732 unRegister.set( meshPart )
1733 self.mesh.ExportPartToDAT( meshPart, f )
1735 self.mesh.ExportDAT(f)
1737 ## Exports the mesh in a file in UNV format
1738 # @param f the file name
1739 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1740 # @ingroup l2_impexp
1741 def ExportUNV(self, f, meshPart=None):
1743 unRegister = genObjUnRegister()
1744 if isinstance( meshPart, list ):
1745 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1746 unRegister.set( meshPart )
1747 self.mesh.ExportPartToUNV( meshPart, f )
1749 self.mesh.ExportUNV(f)
1751 ## Export the mesh in a file in STL format
1752 # @param f the file name
1753 # @param ascii defines the file encoding
1754 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1755 # @ingroup l2_impexp
1756 def ExportSTL(self, f, ascii=1, meshPart=None):
1758 unRegister = genObjUnRegister()
1759 if isinstance( meshPart, list ):
1760 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1761 unRegister.set( meshPart )
1762 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1764 self.mesh.ExportSTL(f, ascii)
1766 ## Exports the mesh in a file in CGNS format
1767 # @param f is the file name
1768 # @param overwrite boolean parameter for overwriting/not overwriting the file
1769 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1770 # @ingroup l2_impexp
1771 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1772 unRegister = genObjUnRegister()
1773 if isinstance( meshPart, list ):
1774 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1775 unRegister.set( meshPart )
1776 if isinstance( meshPart, Mesh ):
1777 meshPart = meshPart.mesh
1779 meshPart = self.mesh
1780 self.mesh.ExportCGNS(meshPart, f, overwrite)
1782 ## Exports the mesh in a file in GMF format.
1783 # GMF files must have .mesh extension for the ASCII format and .meshb for
1784 # the bynary format. Other extensions are not allowed.
1785 # @param f is the file name
1786 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1787 # @ingroup l2_impexp
1788 def ExportGMF(self, f, meshPart=None):
1789 unRegister = genObjUnRegister()
1790 if isinstance( meshPart, list ):
1791 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1792 unRegister.set( meshPart )
1793 if isinstance( meshPart, Mesh ):
1794 meshPart = meshPart.mesh
1796 meshPart = self.mesh
1797 self.mesh.ExportGMF(meshPart, f, True)
1799 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1800 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1801 ## allowing to overwrite the file if it exists or add the exported data to its contents
1802 # @param f the file name
1803 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1804 # @param opt boolean parameter for creating/not creating
1805 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1806 # @param overwrite boolean parameter for overwriting/not overwriting the file
1807 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1808 # - 1D if all mesh nodes lie on OX coordinate axis, or
1809 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1810 # - 3D in the rest cases.
1812 # If @a autoDimension is @c False, the space dimension is always 3.
1813 # @ingroup l2_impexp
1814 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1815 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1817 # Operations with groups:
1818 # ----------------------
1820 ## Creates an empty mesh group
1821 # @param elementType the type of elements in the group
1822 # @param name the name of the mesh group
1823 # @return SMESH_Group
1824 # @ingroup l2_grps_create
1825 def CreateEmptyGroup(self, elementType, name):
1826 return self.mesh.CreateGroup(elementType, name)
1828 ## Creates a mesh group based on the geometric object \a grp
1829 # and gives a \a name, \n if this parameter is not defined
1830 # the name is the same as the geometric group name \n
1831 # Note: Works like GroupOnGeom().
1832 # @param grp a geometric group, a vertex, an edge, a face or a solid
1833 # @param name the name of the mesh group
1834 # @return SMESH_GroupOnGeom
1835 # @ingroup l2_grps_create
1836 def Group(self, grp, name=""):
1837 return self.GroupOnGeom(grp, name)
1839 ## Creates a mesh group based on the geometrical object \a grp
1840 # and gives a \a name, \n if this parameter is not defined
1841 # the name is the same as the geometrical group name
1842 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1843 # @param name the name of the mesh group
1844 # @param typ the type of elements in the group. If not set, it is
1845 # automatically detected by the type of the geometry
1846 # @return SMESH_GroupOnGeom
1847 # @ingroup l2_grps_create
1848 def GroupOnGeom(self, grp, name="", typ=None):
1849 AssureGeomPublished( self, grp, name )
1851 name = grp.GetName()
1853 typ = self._groupTypeFromShape( grp )
1854 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1856 ## Pivate method to get a type of group on geometry
1857 def _groupTypeFromShape( self, shape ):
1858 tgeo = str(shape.GetShapeType())
1859 if tgeo == "VERTEX":
1861 elif tgeo == "EDGE":
1863 elif tgeo == "FACE" or tgeo == "SHELL":
1865 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1867 elif tgeo == "COMPOUND":
1868 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1870 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1871 return self._groupTypeFromShape( sub[0] )
1874 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1877 ## Creates a mesh group with given \a name based on the \a filter which
1878 ## is a special type of group dynamically updating it's contents during
1879 ## mesh modification
1880 # @param typ the type of elements in the group
1881 # @param name the name of the mesh group
1882 # @param filter the filter defining group contents
1883 # @return SMESH_GroupOnFilter
1884 # @ingroup l2_grps_create
1885 def GroupOnFilter(self, typ, name, filter):
1886 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1888 ## Creates a mesh group by the given ids of elements
1889 # @param groupName the name of the mesh group
1890 # @param elementType the type of elements in the group
1891 # @param elemIDs the list of ids
1892 # @return SMESH_Group
1893 # @ingroup l2_grps_create
1894 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1895 group = self.mesh.CreateGroup(elementType, groupName)
1896 if hasattr( elemIDs, "GetIDs" ):
1897 if hasattr( elemIDs, "SetMesh" ):
1898 elemIDs.SetMesh( self.GetMesh() )
1899 group.AddFrom( elemIDs )
1904 ## Creates a mesh group by the given conditions
1905 # @param groupName the name of the mesh group
1906 # @param elementType the type of elements in the group
1907 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1908 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1909 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1910 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1911 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1912 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1913 # @return SMESH_GroupOnFilter
1914 # @ingroup l2_grps_create
1918 CritType=FT_Undefined,
1921 UnaryOp=FT_Undefined,
1923 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1924 group = self.MakeGroupByCriterion(groupName, aCriterion)
1927 ## Creates a mesh group by the given criterion
1928 # @param groupName the name of the mesh group
1929 # @param Criterion the instance of Criterion class
1930 # @return SMESH_GroupOnFilter
1931 # @ingroup l2_grps_create
1932 def MakeGroupByCriterion(self, groupName, Criterion):
1933 return self.MakeGroupByCriteria( groupName, [Criterion] )
1935 ## Creates a mesh group by the given criteria (list of criteria)
1936 # @param groupName the name of the mesh group
1937 # @param theCriteria the list of criteria
1938 # @param binOp binary operator used when binary operator of criteria is undefined
1939 # @return SMESH_GroupOnFilter
1940 # @ingroup l2_grps_create
1941 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1942 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1943 group = self.MakeGroupByFilter(groupName, aFilter)
1946 ## Creates a mesh group by the given filter
1947 # @param groupName the name of the mesh group
1948 # @param theFilter the instance of Filter class
1949 # @return SMESH_GroupOnFilter
1950 # @ingroup l2_grps_create
1951 def MakeGroupByFilter(self, groupName, theFilter):
1952 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1953 #theFilter.SetMesh( self.mesh )
1954 #group.AddFrom( theFilter )
1955 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1959 # @ingroup l2_grps_delete
1960 def RemoveGroup(self, group):
1961 self.mesh.RemoveGroup(group)
1963 ## Removes a group with its contents
1964 # @ingroup l2_grps_delete
1965 def RemoveGroupWithContents(self, group):
1966 self.mesh.RemoveGroupWithContents(group)
1968 ## Gets the list of groups existing in the mesh in the order
1969 # of creation (starting from the oldest one)
1970 # @return a sequence of SMESH_GroupBase
1971 # @ingroup l2_grps_create
1972 def GetGroups(self):
1973 return self.mesh.GetGroups()
1975 ## Gets the number of groups existing in the mesh
1976 # @return the quantity of groups as an integer value
1977 # @ingroup l2_grps_create
1979 return self.mesh.NbGroups()
1981 ## Gets the list of names of groups existing in the mesh
1982 # @return list of strings
1983 # @ingroup l2_grps_create
1984 def GetGroupNames(self):
1985 groups = self.GetGroups()
1987 for group in groups:
1988 names.append(group.GetName())
1991 ## Produces a union of two groups.
1992 # A new group is created. All mesh elements that are
1993 # present in the initial groups are added to the new one
1994 # @return an instance of SMESH_Group
1995 # @ingroup l2_grps_operon
1996 def UnionGroups(self, group1, group2, name):
1997 return self.mesh.UnionGroups(group1, group2, name)
1999 ## Produces a union list of groups.
2000 # New group is created. All mesh elements that are present in
2001 # initial groups are added to the new one
2002 # @return an instance of SMESH_Group
2003 # @ingroup l2_grps_operon
2004 def UnionListOfGroups(self, groups, name):
2005 return self.mesh.UnionListOfGroups(groups, name)
2007 ## Prodices an intersection of two groups.
2008 # A new group is created. All mesh elements that are common
2009 # for the two initial groups are added to the new one.
2010 # @return an instance of SMESH_Group
2011 # @ingroup l2_grps_operon
2012 def IntersectGroups(self, group1, group2, name):
2013 return self.mesh.IntersectGroups(group1, group2, name)
2015 ## Produces an intersection of groups.
2016 # New group is created. All mesh elements that are present in all
2017 # initial groups simultaneously are added to the new one
2018 # @return an instance of SMESH_Group
2019 # @ingroup l2_grps_operon
2020 def IntersectListOfGroups(self, groups, name):
2021 return self.mesh.IntersectListOfGroups(groups, name)
2023 ## Produces a cut of two groups.
2024 # A new group is created. All mesh elements that are present in
2025 # the main group but are not present in the tool group are added to the new one
2026 # @return an instance of SMESH_Group
2027 # @ingroup l2_grps_operon
2028 def CutGroups(self, main_group, tool_group, name):
2029 return self.mesh.CutGroups(main_group, tool_group, name)
2031 ## Produces a cut of groups.
2032 # A new group is created. All mesh elements that are present in main groups
2033 # but do not present in tool groups are added to the new one
2034 # @return an instance of SMESH_Group
2035 # @ingroup l2_grps_operon
2036 def CutListOfGroups(self, main_groups, tool_groups, name):
2037 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2040 # Create a standalone group of entities basing on nodes of other groups.
2041 # \param groups - list of groups, sub-meshes or filters, of any type.
2042 # \param elemType - a type of elements to include to the new group.
2043 # \param name - a name of the new group.
2044 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2045 # basing on number of element nodes common with reference \a groups.
2046 # Meaning of possible values are:
2047 # - SMESH.ALL_NODES - include if all nodes are common,
2048 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2049 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2050 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2051 # \param underlyingOnly - if \c True (default), an element is included to the
2052 # new group provided that it is based on nodes of one element of \a groups.
2053 # @return an instance of SMESH_Group
2054 # @ingroup l2_grps_operon
2055 def CreateDimGroup(self, groups, elemType, name,
2056 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2057 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2059 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2062 ## Convert group on geom into standalone group
2063 # @ingroup l2_grps_delete
2064 def ConvertToStandalone(self, group):
2065 return self.mesh.ConvertToStandalone(group)
2067 # Get some info about mesh:
2068 # ------------------------
2070 ## Returns the log of nodes and elements added or removed
2071 # since the previous clear of the log.
2072 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2073 # @return list of log_block structures:
2078 # @ingroup l1_auxiliary
2079 def GetLog(self, clearAfterGet):
2080 return self.mesh.GetLog(clearAfterGet)
2082 ## Clears the log of nodes and elements added or removed since the previous
2083 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2084 # @ingroup l1_auxiliary
2086 self.mesh.ClearLog()
2088 ## Toggles auto color mode on the object.
2089 # @param theAutoColor the flag which toggles auto color mode.
2090 # @ingroup l1_auxiliary
2091 def SetAutoColor(self, theAutoColor):
2092 self.mesh.SetAutoColor(theAutoColor)
2094 ## Gets flag of object auto color mode.
2095 # @return True or False
2096 # @ingroup l1_auxiliary
2097 def GetAutoColor(self):
2098 return self.mesh.GetAutoColor()
2100 ## Gets the internal ID
2101 # @return integer value, which is the internal Id of the mesh
2102 # @ingroup l1_auxiliary
2104 return self.mesh.GetId()
2107 # @return integer value, which is the study Id of the mesh
2108 # @ingroup l1_auxiliary
2109 def GetStudyId(self):
2110 return self.mesh.GetStudyId()
2112 ## Checks the group names for duplications.
2113 # Consider the maximum group name length stored in MED file.
2114 # @return True or False
2115 # @ingroup l1_auxiliary
2116 def HasDuplicatedGroupNamesMED(self):
2117 return self.mesh.HasDuplicatedGroupNamesMED()
2119 ## Obtains the mesh editor tool
2120 # @return an instance of SMESH_MeshEditor
2121 # @ingroup l1_modifying
2122 def GetMeshEditor(self):
2125 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2126 # can be passed as argument to a method accepting mesh, group or sub-mesh
2127 # @return an instance of SMESH_IDSource
2128 # @ingroup l1_auxiliary
2129 def GetIDSource(self, ids, elemType):
2130 return self.editor.MakeIDSource(ids, elemType)
2133 # Get informations about mesh contents:
2134 # ------------------------------------
2136 ## Gets the mesh stattistic
2137 # @return dictionary type element - count of elements
2138 # @ingroup l1_meshinfo
2139 def GetMeshInfo(self, obj = None):
2140 if not obj: obj = self.mesh
2141 return self.smeshpyD.GetMeshInfo(obj)
2143 ## Returns the number of nodes in the mesh
2144 # @return an integer value
2145 # @ingroup l1_meshinfo
2147 return self.mesh.NbNodes()
2149 ## Returns the number of elements in the mesh
2150 # @return an integer value
2151 # @ingroup l1_meshinfo
2152 def NbElements(self):
2153 return self.mesh.NbElements()
2155 ## Returns the number of 0d elements in the mesh
2156 # @return an integer value
2157 # @ingroup l1_meshinfo
2158 def Nb0DElements(self):
2159 return self.mesh.Nb0DElements()
2161 ## Returns the number of ball discrete elements in the mesh
2162 # @return an integer value
2163 # @ingroup l1_meshinfo
2165 return self.mesh.NbBalls()
2167 ## Returns the number of edges in the mesh
2168 # @return an integer value
2169 # @ingroup l1_meshinfo
2171 return self.mesh.NbEdges()
2173 ## Returns the number of edges with the given order in the mesh
2174 # @param elementOrder the order of elements:
2175 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2176 # @return an integer value
2177 # @ingroup l1_meshinfo
2178 def NbEdgesOfOrder(self, elementOrder):
2179 return self.mesh.NbEdgesOfOrder(elementOrder)
2181 ## Returns the number of faces in the mesh
2182 # @return an integer value
2183 # @ingroup l1_meshinfo
2185 return self.mesh.NbFaces()
2187 ## Returns the number of faces with the given order in the mesh
2188 # @param elementOrder the order of elements:
2189 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2190 # @return an integer value
2191 # @ingroup l1_meshinfo
2192 def NbFacesOfOrder(self, elementOrder):
2193 return self.mesh.NbFacesOfOrder(elementOrder)
2195 ## Returns the number of triangles in the mesh
2196 # @return an integer value
2197 # @ingroup l1_meshinfo
2198 def NbTriangles(self):
2199 return self.mesh.NbTriangles()
2201 ## Returns the number of triangles with the given order in the mesh
2202 # @param elementOrder is the order of elements:
2203 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2204 # @return an integer value
2205 # @ingroup l1_meshinfo
2206 def NbTrianglesOfOrder(self, elementOrder):
2207 return self.mesh.NbTrianglesOfOrder(elementOrder)
2209 ## Returns the number of biquadratic triangles in the mesh
2210 # @return an integer value
2211 # @ingroup l1_meshinfo
2212 def NbBiQuadTriangles(self):
2213 return self.mesh.NbBiQuadTriangles()
2215 ## Returns the number of quadrangles in the mesh
2216 # @return an integer value
2217 # @ingroup l1_meshinfo
2218 def NbQuadrangles(self):
2219 return self.mesh.NbQuadrangles()
2221 ## Returns the number of quadrangles with the given order in the mesh
2222 # @param elementOrder the order of elements:
2223 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2224 # @return an integer value
2225 # @ingroup l1_meshinfo
2226 def NbQuadranglesOfOrder(self, elementOrder):
2227 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2229 ## Returns the number of biquadratic quadrangles in the mesh
2230 # @return an integer value
2231 # @ingroup l1_meshinfo
2232 def NbBiQuadQuadrangles(self):
2233 return self.mesh.NbBiQuadQuadrangles()
2235 ## Returns the number of polygons in the mesh
2236 # @return an integer value
2237 # @ingroup l1_meshinfo
2238 def NbPolygons(self):
2239 return self.mesh.NbPolygons()
2241 ## Returns the number of volumes in the mesh
2242 # @return an integer value
2243 # @ingroup l1_meshinfo
2244 def NbVolumes(self):
2245 return self.mesh.NbVolumes()
2247 ## Returns the number of volumes with the given order in the mesh
2248 # @param elementOrder the order of elements:
2249 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2250 # @return an integer value
2251 # @ingroup l1_meshinfo
2252 def NbVolumesOfOrder(self, elementOrder):
2253 return self.mesh.NbVolumesOfOrder(elementOrder)
2255 ## Returns the number of tetrahedrons in the mesh
2256 # @return an integer value
2257 # @ingroup l1_meshinfo
2259 return self.mesh.NbTetras()
2261 ## Returns the number of tetrahedrons with the given order in the mesh
2262 # @param elementOrder the order of elements:
2263 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2264 # @return an integer value
2265 # @ingroup l1_meshinfo
2266 def NbTetrasOfOrder(self, elementOrder):
2267 return self.mesh.NbTetrasOfOrder(elementOrder)
2269 ## Returns the number of hexahedrons in the mesh
2270 # @return an integer value
2271 # @ingroup l1_meshinfo
2273 return self.mesh.NbHexas()
2275 ## Returns the number of hexahedrons with the given order in the mesh
2276 # @param elementOrder the order of elements:
2277 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2278 # @return an integer value
2279 # @ingroup l1_meshinfo
2280 def NbHexasOfOrder(self, elementOrder):
2281 return self.mesh.NbHexasOfOrder(elementOrder)
2283 ## Returns the number of triquadratic hexahedrons in the mesh
2284 # @return an integer value
2285 # @ingroup l1_meshinfo
2286 def NbTriQuadraticHexas(self):
2287 return self.mesh.NbTriQuadraticHexas()
2289 ## Returns the number of pyramids in the mesh
2290 # @return an integer value
2291 # @ingroup l1_meshinfo
2292 def NbPyramids(self):
2293 return self.mesh.NbPyramids()
2295 ## Returns the number of pyramids with the given order in the mesh
2296 # @param elementOrder the order of elements:
2297 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2298 # @return an integer value
2299 # @ingroup l1_meshinfo
2300 def NbPyramidsOfOrder(self, elementOrder):
2301 return self.mesh.NbPyramidsOfOrder(elementOrder)
2303 ## Returns the number of prisms in the mesh
2304 # @return an integer value
2305 # @ingroup l1_meshinfo
2307 return self.mesh.NbPrisms()
2309 ## Returns the number of prisms with the given order in the mesh
2310 # @param elementOrder the order of elements:
2311 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2312 # @return an integer value
2313 # @ingroup l1_meshinfo
2314 def NbPrismsOfOrder(self, elementOrder):
2315 return self.mesh.NbPrismsOfOrder(elementOrder)
2317 ## Returns the number of hexagonal prisms in the mesh
2318 # @return an integer value
2319 # @ingroup l1_meshinfo
2320 def NbHexagonalPrisms(self):
2321 return self.mesh.NbHexagonalPrisms()
2323 ## Returns the number of polyhedrons in the mesh
2324 # @return an integer value
2325 # @ingroup l1_meshinfo
2326 def NbPolyhedrons(self):
2327 return self.mesh.NbPolyhedrons()
2329 ## Returns the number of submeshes in the mesh
2330 # @return an integer value
2331 # @ingroup l1_meshinfo
2332 def NbSubMesh(self):
2333 return self.mesh.NbSubMesh()
2335 ## Returns the list of mesh elements IDs
2336 # @return the list of integer values
2337 # @ingroup l1_meshinfo
2338 def GetElementsId(self):
2339 return self.mesh.GetElementsId()
2341 ## Returns the list of IDs of mesh elements with the given type
2342 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2343 # @return list of integer values
2344 # @ingroup l1_meshinfo
2345 def GetElementsByType(self, elementType):
2346 return self.mesh.GetElementsByType(elementType)
2348 ## Returns the list of mesh nodes IDs
2349 # @return the list of integer values
2350 # @ingroup l1_meshinfo
2351 def GetNodesId(self):
2352 return self.mesh.GetNodesId()
2354 # Get the information about mesh elements:
2355 # ------------------------------------
2357 ## Returns the type of mesh element
2358 # @return the value from SMESH::ElementType enumeration
2359 # @ingroup l1_meshinfo
2360 def GetElementType(self, id, iselem):
2361 return self.mesh.GetElementType(id, iselem)
2363 ## Returns the geometric type of mesh element
2364 # @return the value from SMESH::EntityType enumeration
2365 # @ingroup l1_meshinfo
2366 def GetElementGeomType(self, id):
2367 return self.mesh.GetElementGeomType(id)
2369 ## Returns the shape type of mesh element
2370 # @return the value from SMESH::GeometryType enumeration
2371 # @ingroup l1_meshinfo
2372 def GetElementShape(self, id):
2373 return self.mesh.GetElementShape(id)
2375 ## Returns the list of submesh elements IDs
2376 # @param Shape a geom object(sub-shape) IOR
2377 # Shape must be the sub-shape of a ShapeToMesh()
2378 # @return the list of integer values
2379 # @ingroup l1_meshinfo
2380 def GetSubMeshElementsId(self, Shape):
2381 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2382 ShapeID = Shape.GetSubShapeIndices()[0]
2385 return self.mesh.GetSubMeshElementsId(ShapeID)
2387 ## Returns the list of submesh nodes IDs
2388 # @param Shape a geom object(sub-shape) IOR
2389 # Shape must be the sub-shape of a ShapeToMesh()
2390 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2391 # @return the list of integer values
2392 # @ingroup l1_meshinfo
2393 def GetSubMeshNodesId(self, Shape, all):
2394 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2395 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2398 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2400 ## Returns type of elements on given shape
2401 # @param Shape a geom object(sub-shape) IOR
2402 # Shape must be a sub-shape of a ShapeToMesh()
2403 # @return element type
2404 # @ingroup l1_meshinfo
2405 def GetSubMeshElementType(self, Shape):
2406 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2407 ShapeID = Shape.GetSubShapeIndices()[0]
2410 return self.mesh.GetSubMeshElementType(ShapeID)
2412 ## Gets the mesh description
2413 # @return string value
2414 # @ingroup l1_meshinfo
2416 return self.mesh.Dump()
2419 # Get the information about nodes and elements of a mesh by its IDs:
2420 # -----------------------------------------------------------
2422 ## Gets XYZ coordinates of a node
2423 # \n If there is no nodes for the given ID - returns an empty list
2424 # @return a list of double precision values
2425 # @ingroup l1_meshinfo
2426 def GetNodeXYZ(self, id):
2427 return self.mesh.GetNodeXYZ(id)
2429 ## Returns list of IDs of inverse elements for the given node
2430 # \n If there is no node for the given ID - returns an empty list
2431 # @return a list of integer values
2432 # @ingroup l1_meshinfo
2433 def GetNodeInverseElements(self, id):
2434 return self.mesh.GetNodeInverseElements(id)
2436 ## @brief Returns the position of a node on the shape
2437 # @return SMESH::NodePosition
2438 # @ingroup l1_meshinfo
2439 def GetNodePosition(self,NodeID):
2440 return self.mesh.GetNodePosition(NodeID)
2442 ## @brief Returns the position of an element on the shape
2443 # @return SMESH::ElementPosition
2444 # @ingroup l1_meshinfo
2445 def GetElementPosition(self,ElemID):
2446 return self.mesh.GetElementPosition(ElemID)
2448 ## If the given element is a node, returns the ID of shape
2449 # \n If there is no node for the given ID - returns -1
2450 # @return an integer value
2451 # @ingroup l1_meshinfo
2452 def GetShapeID(self, id):
2453 return self.mesh.GetShapeID(id)
2455 ## Returns the ID of the result shape after
2456 # FindShape() from SMESH_MeshEditor for the given element
2457 # \n If there is no element for the given ID - returns -1
2458 # @return an integer value
2459 # @ingroup l1_meshinfo
2460 def GetShapeIDForElem(self,id):
2461 return self.mesh.GetShapeIDForElem(id)
2463 ## Returns the number of nodes for the given element
2464 # \n If there is no element for the given ID - returns -1
2465 # @return an integer value
2466 # @ingroup l1_meshinfo
2467 def GetElemNbNodes(self, id):
2468 return self.mesh.GetElemNbNodes(id)
2470 ## Returns the node ID the given (zero based) index for the given element
2471 # \n If there is no element for the given ID - returns -1
2472 # \n If there is no node for the given index - returns -2
2473 # @return an integer value
2474 # @ingroup l1_meshinfo
2475 def GetElemNode(self, id, index):
2476 return self.mesh.GetElemNode(id, index)
2478 ## Returns the IDs of nodes of the given element
2479 # @return a list of integer values
2480 # @ingroup l1_meshinfo
2481 def GetElemNodes(self, id):
2482 return self.mesh.GetElemNodes(id)
2484 ## Returns true if the given node is the medium node in the given quadratic element
2485 # @ingroup l1_meshinfo
2486 def IsMediumNode(self, elementID, nodeID):
2487 return self.mesh.IsMediumNode(elementID, nodeID)
2489 ## Returns true if the given node is the medium node in one of quadratic elements
2490 # @ingroup l1_meshinfo
2491 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2492 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2494 ## Returns the number of edges for the given element
2495 # @ingroup l1_meshinfo
2496 def ElemNbEdges(self, id):
2497 return self.mesh.ElemNbEdges(id)
2499 ## Returns the number of faces for the given element
2500 # @ingroup l1_meshinfo
2501 def ElemNbFaces(self, id):
2502 return self.mesh.ElemNbFaces(id)
2504 ## Returns nodes of given face (counted from zero) for given volumic element.
2505 # @ingroup l1_meshinfo
2506 def GetElemFaceNodes(self,elemId, faceIndex):
2507 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2509 ## Returns three components of normal of given mesh face
2510 # (or an empty array in KO case)
2511 # @ingroup l1_meshinfo
2512 def GetFaceNormal(self, faceId, normalized=False):
2513 return self.mesh.GetFaceNormal(faceId,normalized)
2515 ## Returns an element based on all given nodes.
2516 # @ingroup l1_meshinfo
2517 def FindElementByNodes(self,nodes):
2518 return self.mesh.FindElementByNodes(nodes)
2520 ## Returns true if the given element is a polygon
2521 # @ingroup l1_meshinfo
2522 def IsPoly(self, id):
2523 return self.mesh.IsPoly(id)
2525 ## Returns true if the given element is quadratic
2526 # @ingroup l1_meshinfo
2527 def IsQuadratic(self, id):
2528 return self.mesh.IsQuadratic(id)
2530 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2531 # @ingroup l1_meshinfo
2532 def GetBallDiameter(self, id):
2533 return self.mesh.GetBallDiameter(id)
2535 ## Returns XYZ coordinates of the barycenter of the given element
2536 # \n If there is no element for the given ID - returns an empty list
2537 # @return a list of three double values
2538 # @ingroup l1_meshinfo
2539 def BaryCenter(self, id):
2540 return self.mesh.BaryCenter(id)
2542 ## Passes mesh elements through the given filter and return IDs of fitting elements
2543 # @param theFilter SMESH_Filter
2544 # @return a list of ids
2545 # @ingroup l1_controls
2546 def GetIdsFromFilter(self, theFilter):
2547 theFilter.SetMesh( self.mesh )
2548 return theFilter.GetIDs()
2550 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2551 # Returns a list of special structures (borders).
2552 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2553 # @ingroup l1_controls
2554 def GetFreeBorders(self):
2555 aFilterMgr = self.smeshpyD.CreateFilterManager()
2556 aPredicate = aFilterMgr.CreateFreeEdges()
2557 aPredicate.SetMesh(self.mesh)
2558 aBorders = aPredicate.GetBorders()
2559 aFilterMgr.UnRegister()
2563 # Get mesh measurements information:
2564 # ------------------------------------
2566 ## Get minimum distance between two nodes, elements or distance to the origin
2567 # @param id1 first node/element id
2568 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2569 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2570 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2571 # @return minimum distance value
2572 # @sa GetMinDistance()
2573 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2574 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2575 return aMeasure.value
2577 ## Get measure structure specifying minimum distance data between two objects
2578 # @param id1 first node/element id
2579 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2580 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2581 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2582 # @return Measure structure
2584 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2586 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2588 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2591 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2593 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2598 aMeasurements = self.smeshpyD.CreateMeasurements()
2599 aMeasure = aMeasurements.MinDistance(id1, id2)
2600 genObjUnRegister([aMeasurements,id1, id2])
2603 ## Get bounding box of the specified object(s)
2604 # @param objects single source object or list of source objects or list of nodes/elements IDs
2605 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2606 # @c False specifies that @a objects are nodes
2607 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2608 # @sa GetBoundingBox()
2609 def BoundingBox(self, objects=None, isElem=False):
2610 result = self.GetBoundingBox(objects, isElem)
2614 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2617 ## Get measure structure specifying bounding box data of the specified object(s)
2618 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2619 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2620 # @c False specifies that @a objects are nodes
2621 # @return Measure structure
2623 def GetBoundingBox(self, IDs=None, isElem=False):
2626 elif isinstance(IDs, tuple):
2628 if not isinstance(IDs, list):
2630 if len(IDs) > 0 and isinstance(IDs[0], int):
2633 unRegister = genObjUnRegister()
2635 if isinstance(o, Mesh):
2636 srclist.append(o.mesh)
2637 elif hasattr(o, "_narrow"):
2638 src = o._narrow(SMESH.SMESH_IDSource)
2639 if src: srclist.append(src)
2641 elif isinstance(o, list):
2643 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2645 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2646 unRegister.set( srclist[-1] )
2649 aMeasurements = self.smeshpyD.CreateMeasurements()
2650 unRegister.set( aMeasurements )
2651 aMeasure = aMeasurements.BoundingBox(srclist)
2654 # Mesh edition (SMESH_MeshEditor functionality):
2655 # ---------------------------------------------
2657 ## Removes the elements from the mesh by ids
2658 # @param IDsOfElements is a list of ids of elements to remove
2659 # @return True or False
2660 # @ingroup l2_modif_del
2661 def RemoveElements(self, IDsOfElements):
2662 return self.editor.RemoveElements(IDsOfElements)
2664 ## Removes nodes from mesh by ids
2665 # @param IDsOfNodes is a list of ids of nodes to remove
2666 # @return True or False
2667 # @ingroup l2_modif_del
2668 def RemoveNodes(self, IDsOfNodes):
2669 return self.editor.RemoveNodes(IDsOfNodes)
2671 ## Removes all orphan (free) nodes from mesh
2672 # @return number of the removed nodes
2673 # @ingroup l2_modif_del
2674 def RemoveOrphanNodes(self):
2675 return self.editor.RemoveOrphanNodes()
2677 ## Add a node to the mesh by coordinates
2678 # @return Id of the new node
2679 # @ingroup l2_modif_add
2680 def AddNode(self, x, y, z):
2681 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2682 if hasVars: self.mesh.SetParameters(Parameters)
2683 return self.editor.AddNode( x, y, z)
2685 ## Creates a 0D element on a node with given number.
2686 # @param IDOfNode the ID of node for creation of the element.
2687 # @return the Id of the new 0D element
2688 # @ingroup l2_modif_add
2689 def Add0DElement(self, IDOfNode):
2690 return self.editor.Add0DElement(IDOfNode)
2692 ## Create 0D elements on all nodes of the given elements except those
2693 # nodes on which a 0D element already exists.
2694 # @param theObject an object on whose nodes 0D elements will be created.
2695 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2696 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2697 # @param theGroupName optional name of a group to add 0D elements created
2698 # and/or found on nodes of \a theObject.
2699 # @return an object (a new group or a temporary SMESH_IDSource) holding
2700 # IDs of new and/or found 0D elements. IDs of 0D elements
2701 # can be retrieved from the returned object by calling GetIDs()
2702 # @ingroup l2_modif_add
2703 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2704 unRegister = genObjUnRegister()
2705 if isinstance( theObject, Mesh ):
2706 theObject = theObject.GetMesh()
2707 if isinstance( theObject, list ):
2708 theObject = self.GetIDSource( theObject, SMESH.ALL )
2709 unRegister.set( theObject )
2710 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2712 ## Creates a ball element on a node with given ID.
2713 # @param IDOfNode the ID of node for creation of the element.
2714 # @param diameter the bal diameter.
2715 # @return the Id of the new ball element
2716 # @ingroup l2_modif_add
2717 def AddBall(self, IDOfNode, diameter):
2718 return self.editor.AddBall( IDOfNode, diameter )
2720 ## Creates a linear or quadratic edge (this is determined
2721 # by the number of given nodes).
2722 # @param IDsOfNodes the list of node IDs for creation of the element.
2723 # The order of nodes in this list should correspond to the description
2724 # of MED. \n This description is located by the following link:
2725 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2726 # @return the Id of the new edge
2727 # @ingroup l2_modif_add
2728 def AddEdge(self, IDsOfNodes):
2729 return self.editor.AddEdge(IDsOfNodes)
2731 ## Creates a linear or quadratic face (this is determined
2732 # by the number of given nodes).
2733 # @param IDsOfNodes the list of node IDs for creation of the element.
2734 # The order of nodes in this list should correspond to the description
2735 # of MED. \n This description is located by the following link:
2736 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2737 # @return the Id of the new face
2738 # @ingroup l2_modif_add
2739 def AddFace(self, IDsOfNodes):
2740 return self.editor.AddFace(IDsOfNodes)
2742 ## Adds a polygonal face to the mesh by the list of node IDs
2743 # @param IdsOfNodes the list of node IDs for creation of the element.
2744 # @return the Id of the new face
2745 # @ingroup l2_modif_add
2746 def AddPolygonalFace(self, IdsOfNodes):
2747 return self.editor.AddPolygonalFace(IdsOfNodes)
2749 ## Creates both simple and quadratic volume (this is determined
2750 # by the number of given nodes).
2751 # @param IDsOfNodes the list of node IDs for creation of the element.
2752 # The order of nodes in this list should correspond to the description
2753 # of MED. \n This description is located by the following link:
2754 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2755 # @return the Id of the new volumic element
2756 # @ingroup l2_modif_add
2757 def AddVolume(self, IDsOfNodes):
2758 return self.editor.AddVolume(IDsOfNodes)
2760 ## Creates a volume of many faces, giving nodes for each face.
2761 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2762 # @param Quantities the list of integer values, Quantities[i]
2763 # gives the quantity of nodes in face number i.
2764 # @return the Id of the new volumic element
2765 # @ingroup l2_modif_add
2766 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2767 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2769 ## Creates a volume of many faces, giving the IDs of the existing faces.
2770 # @param IdsOfFaces the list of face IDs for volume creation.
2772 # Note: The created volume will refer only to the nodes
2773 # of the given faces, not to the faces themselves.
2774 # @return the Id of the new volumic element
2775 # @ingroup l2_modif_add
2776 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2777 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2780 ## @brief Binds a node to a vertex
2781 # @param NodeID a node ID
2782 # @param Vertex a vertex or vertex ID
2783 # @return True if succeed else raises an exception
2784 # @ingroup l2_modif_add
2785 def SetNodeOnVertex(self, NodeID, Vertex):
2786 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2787 VertexID = Vertex.GetSubShapeIndices()[0]
2791 self.editor.SetNodeOnVertex(NodeID, VertexID)
2792 except SALOME.SALOME_Exception, inst:
2793 raise ValueError, inst.details.text
2797 ## @brief Stores the node position on an edge
2798 # @param NodeID a node ID
2799 # @param Edge an edge or edge ID
2800 # @param paramOnEdge a parameter on the edge where the node is located
2801 # @return True if succeed else raises an exception
2802 # @ingroup l2_modif_add
2803 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2804 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2805 EdgeID = Edge.GetSubShapeIndices()[0]
2809 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2810 except SALOME.SALOME_Exception, inst:
2811 raise ValueError, inst.details.text
2814 ## @brief Stores node position on a face
2815 # @param NodeID a node ID
2816 # @param Face a face or face ID
2817 # @param u U parameter on the face where the node is located
2818 # @param v V parameter on the face where the node is located
2819 # @return True if succeed else raises an exception
2820 # @ingroup l2_modif_add
2821 def SetNodeOnFace(self, NodeID, Face, u, v):
2822 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2823 FaceID = Face.GetSubShapeIndices()[0]
2827 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2828 except SALOME.SALOME_Exception, inst:
2829 raise ValueError, inst.details.text
2832 ## @brief Binds a node to a solid
2833 # @param NodeID a node ID
2834 # @param Solid a solid or solid ID
2835 # @return True if succeed else raises an exception
2836 # @ingroup l2_modif_add
2837 def SetNodeInVolume(self, NodeID, Solid):
2838 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2839 SolidID = Solid.GetSubShapeIndices()[0]
2843 self.editor.SetNodeInVolume(NodeID, SolidID)
2844 except SALOME.SALOME_Exception, inst:
2845 raise ValueError, inst.details.text
2848 ## @brief Bind an element to a shape
2849 # @param ElementID an element ID
2850 # @param Shape a shape or shape ID
2851 # @return True if succeed else raises an exception
2852 # @ingroup l2_modif_add
2853 def SetMeshElementOnShape(self, ElementID, Shape):
2854 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2855 ShapeID = Shape.GetSubShapeIndices()[0]
2859 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2860 except SALOME.SALOME_Exception, inst:
2861 raise ValueError, inst.details.text
2865 ## Moves the node with the given id
2866 # @param NodeID the id of the node
2867 # @param x a new X coordinate
2868 # @param y a new Y coordinate
2869 # @param z a new Z coordinate
2870 # @return True if succeed else False
2871 # @ingroup l2_modif_movenode
2872 def MoveNode(self, NodeID, x, y, z):
2873 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2874 if hasVars: self.mesh.SetParameters(Parameters)
2875 return self.editor.MoveNode(NodeID, x, y, z)
2877 ## Finds the node closest to a point and moves it to a point location
2878 # @param x the X coordinate of a point
2879 # @param y the Y coordinate of a point
2880 # @param z the Z coordinate of a point
2881 # @param NodeID if specified (>0), the node with this ID is moved,
2882 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2883 # @return the ID of a node
2884 # @ingroup l2_modif_throughp
2885 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2886 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2887 if hasVars: self.mesh.SetParameters(Parameters)
2888 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2890 ## Finds the node closest to a point
2891 # @param x the X coordinate of a point
2892 # @param y the Y coordinate of a point
2893 # @param z the Z coordinate of a point
2894 # @return the ID of a node
2895 # @ingroup l2_modif_throughp
2896 def FindNodeClosestTo(self, x, y, z):
2897 #preview = self.mesh.GetMeshEditPreviewer()
2898 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2899 return self.editor.FindNodeClosestTo(x, y, z)
2901 ## Finds the elements where a point lays IN or ON
2902 # @param x the X coordinate of a point
2903 # @param y the Y coordinate of a point
2904 # @param z the Z coordinate of a point
2905 # @param elementType type of elements to find (SMESH.ALL type
2906 # means elements of any type excluding nodes, discrete and 0D elements)
2907 # @param meshPart a part of mesh (group, sub-mesh) to search within
2908 # @return list of IDs of found elements
2909 # @ingroup l2_modif_throughp
2910 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2912 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2914 return self.editor.FindElementsByPoint(x, y, z, elementType)
2916 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2917 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2918 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2920 def GetPointState(self, x, y, z):
2921 return self.editor.GetPointState(x, y, z)
2923 ## Finds the node closest to a point and moves it to a point location
2924 # @param x the X coordinate of a point
2925 # @param y the Y coordinate of a point
2926 # @param z the Z coordinate of a point
2927 # @return the ID of a moved node
2928 # @ingroup l2_modif_throughp
2929 def MeshToPassThroughAPoint(self, x, y, z):
2930 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2932 ## Replaces two neighbour triangles sharing Node1-Node2 link
2933 # with the triangles built on the same 4 nodes but having other common link.
2934 # @param NodeID1 the ID of the first node
2935 # @param NodeID2 the ID of the second node
2936 # @return false if proper faces were not found
2937 # @ingroup l2_modif_invdiag
2938 def InverseDiag(self, NodeID1, NodeID2):
2939 return self.editor.InverseDiag(NodeID1, NodeID2)
2941 ## Replaces two neighbour triangles sharing Node1-Node2 link
2942 # with a quadrangle built on the same 4 nodes.
2943 # @param NodeID1 the ID of the first node
2944 # @param NodeID2 the ID of the second node
2945 # @return false if proper faces were not found
2946 # @ingroup l2_modif_unitetri
2947 def DeleteDiag(self, NodeID1, NodeID2):
2948 return self.editor.DeleteDiag(NodeID1, NodeID2)
2950 ## Reorients elements by ids
2951 # @param IDsOfElements if undefined reorients all mesh elements
2952 # @return True if succeed else False
2953 # @ingroup l2_modif_changori
2954 def Reorient(self, IDsOfElements=None):
2955 if IDsOfElements == None:
2956 IDsOfElements = self.GetElementsId()
2957 return self.editor.Reorient(IDsOfElements)
2959 ## Reorients all elements of the object
2960 # @param theObject mesh, submesh or group
2961 # @return True if succeed else False
2962 # @ingroup l2_modif_changori
2963 def ReorientObject(self, theObject):
2964 if ( isinstance( theObject, Mesh )):
2965 theObject = theObject.GetMesh()
2966 return self.editor.ReorientObject(theObject)
2968 ## Reorient faces contained in \a the2DObject.
2969 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2970 # @param theDirection is a desired direction of normal of \a theFace.
2971 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2972 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2973 # compared with theDirection. It can be either ID of face or a point
2974 # by which the face will be found. The point can be given as either
2975 # a GEOM vertex or a list of point coordinates.
2976 # @return number of reoriented faces
2977 # @ingroup l2_modif_changori
2978 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2979 unRegister = genObjUnRegister()
2981 if isinstance( the2DObject, Mesh ):
2982 the2DObject = the2DObject.GetMesh()
2983 if isinstance( the2DObject, list ):
2984 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2985 unRegister.set( the2DObject )
2986 # check theDirection
2987 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2988 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2989 if isinstance( theDirection, list ):
2990 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2991 # prepare theFace and thePoint
2992 theFace = theFaceOrPoint
2993 thePoint = PointStruct(0,0,0)
2994 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2995 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2997 if isinstance( theFaceOrPoint, list ):
2998 thePoint = PointStruct( *theFaceOrPoint )
3000 if isinstance( theFaceOrPoint, PointStruct ):
3001 thePoint = theFaceOrPoint
3003 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3005 ## Reorient faces according to adjacent volumes.
3006 # @param the2DObject is a mesh, sub-mesh, group or list of
3007 # either IDs of faces or face groups.
3008 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3009 # @param theOutsideNormal to orient faces to have their normals
3010 # pointing either \a outside or \a inside the adjacent volumes.
3011 # @return number of reoriented faces.
3012 # @ingroup l2_modif_changori
3013 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3014 unRegister = genObjUnRegister()
3016 if not isinstance( the2DObject, list ):
3017 the2DObject = [ the2DObject ]
3018 elif the2DObject and isinstance( the2DObject[0], int ):
3019 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3020 unRegister.set( the2DObject )
3021 the2DObject = [ the2DObject ]
3022 for i,obj2D in enumerate( the2DObject ):
3023 if isinstance( obj2D, Mesh ):
3024 the2DObject[i] = obj2D.GetMesh()
3025 if isinstance( obj2D, list ):
3026 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3027 unRegister.set( the2DObject[i] )
3029 if isinstance( the3DObject, Mesh ):
3030 the3DObject = the3DObject.GetMesh()
3031 if isinstance( the3DObject, list ):
3032 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3033 unRegister.set( the3DObject )
3034 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3036 ## Fuses the neighbouring triangles into quadrangles.
3037 # @param IDsOfElements The triangles to be fused,
3038 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3039 # choose a neighbour to fuse with.
3040 # @param MaxAngle is the maximum angle between element normals at which the fusion
3041 # is still performed; theMaxAngle is mesured in radians.
3042 # Also it could be a name of variable which defines angle in degrees.
3043 # @return TRUE in case of success, FALSE otherwise.
3044 # @ingroup l2_modif_unitetri
3045 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3046 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3047 self.mesh.SetParameters(Parameters)
3048 if not IDsOfElements:
3049 IDsOfElements = self.GetElementsId()
3050 Functor = self.smeshpyD.GetFunctor(theCriterion)
3051 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3053 ## Fuses the neighbouring triangles of the object into quadrangles
3054 # @param theObject is mesh, submesh or group
3055 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3056 # choose a neighbour to fuse with.
3057 # @param MaxAngle a max angle between element normals at which the fusion
3058 # is still performed; theMaxAngle is mesured in radians.
3059 # @return TRUE in case of success, FALSE otherwise.
3060 # @ingroup l2_modif_unitetri
3061 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3062 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3063 self.mesh.SetParameters(Parameters)
3064 if isinstance( theObject, Mesh ):
3065 theObject = theObject.GetMesh()
3066 Functor = self.smeshpyD.GetFunctor(theCriterion)
3067 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3069 ## Splits quadrangles into triangles.
3070 # @param IDsOfElements the faces to be splitted.
3071 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3072 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3073 # value, then quadrangles will be split by the smallest diagonal.
3074 # @return TRUE in case of success, FALSE otherwise.
3075 # @ingroup l2_modif_cutquadr
3076 def QuadToTri (self, IDsOfElements, theCriterion = None):
3077 if IDsOfElements == []:
3078 IDsOfElements = self.GetElementsId()
3079 if theCriterion is None:
3080 theCriterion = FT_MaxElementLength2D
3081 Functor = self.smeshpyD.GetFunctor(theCriterion)
3082 return self.editor.QuadToTri(IDsOfElements, Functor)
3084 ## Splits quadrangles into triangles.
3085 # @param theObject the object from which the list of elements is taken,
3086 # this is mesh, submesh or group
3087 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3088 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3089 # value, then quadrangles will be split by the smallest diagonal.
3090 # @return TRUE in case of success, FALSE otherwise.
3091 # @ingroup l2_modif_cutquadr
3092 def QuadToTriObject (self, theObject, theCriterion = None):
3093 if ( isinstance( theObject, Mesh )):
3094 theObject = theObject.GetMesh()
3095 if theCriterion is None:
3096 theCriterion = FT_MaxElementLength2D
3097 Functor = self.smeshpyD.GetFunctor(theCriterion)
3098 return self.editor.QuadToTriObject(theObject, Functor)
3100 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3102 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3103 # group or a list of face IDs. By default all quadrangles are split
3104 # @ingroup l2_modif_cutquadr
3105 def QuadTo4Tri (self, theElements=[]):
3106 unRegister = genObjUnRegister()
3107 if isinstance( theElements, Mesh ):
3108 theElements = theElements.mesh
3109 elif not theElements:
3110 theElements = self.mesh
3111 elif isinstance( theElements, list ):
3112 theElements = self.GetIDSource( theElements, SMESH.FACE )
3113 unRegister.set( theElements )
3114 return self.editor.QuadTo4Tri( theElements )
3116 ## Splits quadrangles into triangles.
3117 # @param IDsOfElements the faces to be splitted
3118 # @param Diag13 is used to choose a diagonal for splitting.
3119 # @return TRUE in case of success, FALSE otherwise.
3120 # @ingroup l2_modif_cutquadr
3121 def SplitQuad (self, IDsOfElements, Diag13):
3122 if IDsOfElements == []:
3123 IDsOfElements = self.GetElementsId()
3124 return self.editor.SplitQuad(IDsOfElements, Diag13)
3126 ## Splits quadrangles into triangles.
3127 # @param theObject the object from which the list of elements is taken,
3128 # this is mesh, submesh or group
3129 # @param Diag13 is used to choose a diagonal for splitting.
3130 # @return TRUE in case of success, FALSE otherwise.
3131 # @ingroup l2_modif_cutquadr
3132 def SplitQuadObject (self, theObject, Diag13):
3133 if ( isinstance( theObject, Mesh )):
3134 theObject = theObject.GetMesh()
3135 return self.editor.SplitQuadObject(theObject, Diag13)
3137 ## Finds a better splitting of the given quadrangle.
3138 # @param IDOfQuad the ID of the quadrangle to be splitted.
3139 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3140 # choose a diagonal for splitting.
3141 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3142 # diagonal is better, 0 if error occurs.
3143 # @ingroup l2_modif_cutquadr
3144 def BestSplit (self, IDOfQuad, theCriterion):
3145 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3147 ## Splits volumic elements into tetrahedrons
3148 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3149 # @param method flags passing splitting method:
3150 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3151 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3152 # @ingroup l2_modif_cutquadr
3153 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3154 unRegister = genObjUnRegister()
3155 if isinstance( elems, Mesh ):
3156 elems = elems.GetMesh()
3157 if ( isinstance( elems, list )):
3158 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3159 unRegister.set( elems )
3160 self.editor.SplitVolumesIntoTetra(elems, method)
3162 ## Splits hexahedra into prisms
3163 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3164 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3165 # gives a normal vector defining facets to split into triangles.
3166 # @a startHexPoint can be either a triple of coordinates or a vertex.
3167 # @param facetNormal a normal to a facet to split into triangles of a
3168 # hexahedron found by @a startHexPoint.
3169 # @a facetNormal can be either a triple of coordinates or an edge.
3170 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3171 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3172 # @param allDomains if @c False, only hexahedra adjacent to one closest
3173 # to @a startHexPoint are split, else @a startHexPoint
3174 # is used to find the facet to split in all domains present in @a elems.
3175 # @ingroup l2_modif_cutquadr
3176 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3177 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3179 unRegister = genObjUnRegister()
3180 if isinstance( elems, Mesh ):
3181 elems = elems.GetMesh()
3182 if ( isinstance( elems, list )):
3183 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3184 unRegister.set( elems )
3187 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3188 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3189 elif isinstance( startHexPoint, list ):
3190 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3193 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3194 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3195 elif isinstance( facetNormal, list ):
3196 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3199 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3201 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3203 ## Splits quadrangle faces near triangular facets of volumes
3205 # @ingroup l1_auxiliary
3206 def SplitQuadsNearTriangularFacets(self):
3207 faces_array = self.GetElementsByType(SMESH.FACE)
3208 for face_id in faces_array:
3209 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3210 quad_nodes = self.mesh.GetElemNodes(face_id)
3211 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3212 isVolumeFound = False
3213 for node1_elem in node1_elems:
3214 if not isVolumeFound:
3215 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3216 nb_nodes = self.GetElemNbNodes(node1_elem)
3217 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3218 volume_elem = node1_elem
3219 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3220 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3221 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3222 isVolumeFound = True
3223 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3224 self.SplitQuad([face_id], False) # diagonal 2-4
3225 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3226 isVolumeFound = True
3227 self.SplitQuad([face_id], True) # diagonal 1-3
3228 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3229 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3230 isVolumeFound = True
3231 self.SplitQuad([face_id], True) # diagonal 1-3
3233 ## @brief Splits hexahedrons into tetrahedrons.
3235 # This operation uses pattern mapping functionality for splitting.
3236 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3237 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3238 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3239 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3240 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3241 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3242 # @return TRUE in case of success, FALSE otherwise.
3243 # @ingroup l1_auxiliary
3244 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3245 # Pattern: 5.---------.6
3250 # (0,0,1) 4.---------.7 * |
3257 # (0,0,0) 0.---------.3
3258 pattern_tetra = "!!! Nb of points: \n 8 \n\
3268 !!! Indices of points of 6 tetras: \n\
3276 pattern = self.smeshpyD.GetPattern()
3277 isDone = pattern.LoadFromFile(pattern_tetra)
3279 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3282 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3283 isDone = pattern.MakeMesh(self.mesh, False, False)
3284 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3286 # split quafrangle faces near triangular facets of volumes
3287 self.SplitQuadsNearTriangularFacets()
3291 ## @brief Split hexahedrons into prisms.
3293 # Uses the pattern mapping functionality for splitting.
3294 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3295 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3296 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3297 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3298 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3299 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3300 # @return TRUE in case of success, FALSE otherwise.
3301 # @ingroup l1_auxiliary
3302 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3303 # Pattern: 5.---------.6
3308 # (0,0,1) 4.---------.7 |
3315 # (0,0,0) 0.---------.3
3316 pattern_prism = "!!! Nb of points: \n 8 \n\
3326 !!! Indices of points of 2 prisms: \n\
3330 pattern = self.smeshpyD.GetPattern()
3331 isDone = pattern.LoadFromFile(pattern_prism)
3333 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3336 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3337 isDone = pattern.MakeMesh(self.mesh, False, False)
3338 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3340 # Splits quafrangle faces near triangular facets of volumes
3341 self.SplitQuadsNearTriangularFacets()
3345 ## Smoothes elements
3346 # @param IDsOfElements the list if ids of elements to smooth
3347 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3348 # Note that nodes built on edges and boundary nodes are always fixed.
3349 # @param MaxNbOfIterations the maximum number of iterations
3350 # @param MaxAspectRatio varies in range [1.0, inf]
3351 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3352 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3353 # @return TRUE in case of success, FALSE otherwise.
3354 # @ingroup l2_modif_smooth
3355 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3356 MaxNbOfIterations, MaxAspectRatio, Method):
3357 if IDsOfElements == []:
3358 IDsOfElements = self.GetElementsId()
3359 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3360 self.mesh.SetParameters(Parameters)
3361 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3362 MaxNbOfIterations, MaxAspectRatio, Method)
3364 ## Smoothes elements which belong to the given object
3365 # @param theObject the object to smooth
3366 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3367 # Note that nodes built on edges and boundary nodes are always fixed.
3368 # @param MaxNbOfIterations the maximum number of iterations
3369 # @param MaxAspectRatio varies in range [1.0, inf]
3370 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3371 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3372 # @return TRUE in case of success, FALSE otherwise.
3373 # @ingroup l2_modif_smooth
3374 def SmoothObject(self, theObject, IDsOfFixedNodes,
3375 MaxNbOfIterations, MaxAspectRatio, Method):
3376 if ( isinstance( theObject, Mesh )):
3377 theObject = theObject.GetMesh()
3378 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3379 MaxNbOfIterations, MaxAspectRatio, Method)
3381 ## Parametrically smoothes the given elements
3382 # @param IDsOfElements the list if ids of elements to smooth
3383 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3384 # Note that nodes built on edges and boundary nodes are always fixed.
3385 # @param MaxNbOfIterations the maximum number of iterations
3386 # @param MaxAspectRatio varies in range [1.0, inf]
3387 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3388 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3389 # @return TRUE in case of success, FALSE otherwise.
3390 # @ingroup l2_modif_smooth
3391 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3392 MaxNbOfIterations, MaxAspectRatio, Method):
3393 if IDsOfElements == []:
3394 IDsOfElements = self.GetElementsId()
3395 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3396 self.mesh.SetParameters(Parameters)
3397 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3398 MaxNbOfIterations, MaxAspectRatio, Method)
3400 ## Parametrically smoothes the elements which belong to the given object
3401 # @param theObject the object to smooth
3402 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3403 # Note that nodes built on edges and boundary nodes are always fixed.
3404 # @param MaxNbOfIterations the maximum number of iterations
3405 # @param MaxAspectRatio varies in range [1.0, inf]
3406 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3407 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3408 # @return TRUE in case of success, FALSE otherwise.
3409 # @ingroup l2_modif_smooth
3410 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3411 MaxNbOfIterations, MaxAspectRatio, Method):
3412 if ( isinstance( theObject, Mesh )):
3413 theObject = theObject.GetMesh()
3414 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3415 MaxNbOfIterations, MaxAspectRatio, Method)
3417 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3418 # them with quadratic with the same id.
3419 # @param theForce3d new node creation method:
3420 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3421 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3422 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3423 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3424 # @ingroup l2_modif_tofromqu
3425 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3426 if isinstance( theSubMesh, Mesh ):
3427 theSubMesh = theSubMesh.mesh
3429 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3432 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3434 self.editor.ConvertToQuadratic(theForce3d)
3435 error = self.editor.GetLastError()
3436 if error and error.comment:
3439 ## Converts the mesh from quadratic to ordinary,
3440 # deletes old quadratic elements, \n replacing
3441 # them with ordinary mesh elements with the same id.
3442 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3443 # @ingroup l2_modif_tofromqu
3444 def ConvertFromQuadratic(self, theSubMesh=None):
3446 self.editor.ConvertFromQuadraticObject(theSubMesh)
3448 return self.editor.ConvertFromQuadratic()
3450 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3451 # @return TRUE if operation has been completed successfully, FALSE otherwise
3452 # @ingroup l2_modif_edit
3453 def Make2DMeshFrom3D(self):
3454 return self.editor. Make2DMeshFrom3D()
3456 ## Creates missing boundary elements
3457 # @param elements - elements whose boundary is to be checked:
3458 # mesh, group, sub-mesh or list of elements
3459 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3460 # @param dimension - defines type of boundary elements to create:
3461 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3462 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3463 # @param groupName - a name of group to store created boundary elements in,
3464 # "" means not to create the group
3465 # @param meshName - a name of new mesh to store created boundary elements in,
3466 # "" means not to create the new mesh
3467 # @param toCopyElements - if true, the checked elements will be copied into
3468 # the new mesh else only boundary elements will be copied into the new mesh
3469 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3470 # boundary elements will be copied into the new mesh
3471 # @return tuple (mesh, group) where boundary elements were added to
3472 # @ingroup l2_modif_edit
3473 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3474 toCopyElements=False, toCopyExistingBondary=False):
3475 unRegister = genObjUnRegister()
3476 if isinstance( elements, Mesh ):
3477 elements = elements.GetMesh()
3478 if ( isinstance( elements, list )):
3479 elemType = SMESH.ALL
3480 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3481 elements = self.editor.MakeIDSource(elements, elemType)
3482 unRegister.set( elements )
3483 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3484 toCopyElements,toCopyExistingBondary)
3485 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3489 # @brief Creates missing boundary elements around either the whole mesh or
3490 # groups of elements
3491 # @param dimension - defines type of boundary elements to create
3492 # @param groupName - a name of group to store all boundary elements in,
3493 # "" means not to create the group
3494 # @param meshName - a name of a new mesh, which is a copy of the initial
3495 # mesh + created boundary elements; "" means not to create the new mesh
3496 # @param toCopyAll - if true, the whole initial mesh will be copied into
3497 # the new mesh else only boundary elements will be copied into the new mesh
3498 # @param groups - groups of elements to make boundary around
3499 # @retval tuple( long, mesh, groups )
3500 # long - number of added boundary elements
3501 # mesh - the mesh where elements were added to
3502 # group - the group of boundary elements or None
3504 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3505 toCopyAll=False, groups=[]):
3506 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3508 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3509 return nb, mesh, group
3511 ## Renumber mesh nodes (Obsolete, does nothing)
3512 # @ingroup l2_modif_renumber
3513 def RenumberNodes(self):
3514 self.editor.RenumberNodes()
3516 ## Renumber mesh elements (Obsole, does nothing)
3517 # @ingroup l2_modif_renumber
3518 def RenumberElements(self):
3519 self.editor.RenumberElements()
3521 ## Private method converting \a arg into a list of SMESH_IdSource's
3522 def _getIdSourceList(self, arg, idType, unRegister):
3523 if arg and isinstance( arg, list ):
3524 if isinstance( arg[0], int ):
3525 arg = self.GetIDSource( arg, idType )
3526 unRegister.set( arg )
3527 elif isinstance( arg[0], Mesh ):
3528 arg[0] = arg[0].GetMesh()
3529 elif isinstance( arg, Mesh ):
3531 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3535 ## Generates new elements by rotation of the given elements and nodes around the axis
3536 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3537 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3538 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3539 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3540 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3541 # which defines angle in degrees
3542 # @param NbOfSteps the number of steps
3543 # @param Tolerance tolerance
3544 # @param MakeGroups forces the generation of new groups from existing ones
3545 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3546 # of all steps, else - size of each step
3547 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3548 # @ingroup l2_modif_extrurev
3549 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3550 MakeGroups=False, TotalAngle=False):
3551 unRegister = genObjUnRegister()
3552 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3553 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3554 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3556 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3557 Axis = self.smeshpyD.GetDirStruct( Axis )
3558 if isinstance( Axis, list ):
3559 Axis = SMESH.AxisStruct( *Axis )
3561 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3562 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3563 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3564 self.mesh.SetParameters(Parameters)
3565 if TotalAngle and NbOfSteps:
3566 AngleInRadians /= NbOfSteps
3567 return self.editor.RotationSweepObjects( nodes, edges, faces,
3568 Axis, AngleInRadians,
3569 NbOfSteps, Tolerance, MakeGroups)
3571 ## Generates new elements by rotation of the elements around the axis
3572 # @param IDsOfElements the list of ids of elements to sweep
3573 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3574 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3575 # @param NbOfSteps the number of steps
3576 # @param Tolerance tolerance
3577 # @param MakeGroups forces the generation of new groups from existing ones
3578 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3579 # of all steps, else - size of each step
3580 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3581 # @ingroup l2_modif_extrurev
3582 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3583 MakeGroups=False, TotalAngle=False):
3584 unRegister = genObjUnRegister()
3585 if IDsOfElements == []:
3586 IDsOfElements = self.mesh
3587 if IDsOfElements and \
3588 isinstance( IDsOfElements, list ) and \
3589 isinstance( IDsOfElements[0], int ):
3590 IDsOfElements = self.GetIDSource( IDsOfElements, SMESH.ALL )
3591 unRegister.set( IDsOfElements )
3592 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3593 Axis = self.smeshpyD.GetAxisStruct(Axis)
3594 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3595 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3596 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3597 self.mesh.SetParameters(Parameters)
3598 if TotalAngle and NbOfSteps:
3599 AngleInRadians /= NbOfSteps
3600 return self.editor.RotationSweepObjects([],[IDsOfElements],[IDsOfElements], Axis,
3601 AngleInRadians, NbOfSteps, Tolerance, MakeGroups)
3603 ## Generates new elements by rotation of the elements of object around the axis
3604 # @param theObject object which elements should be sweeped.
3605 # It can be a mesh, a sub mesh or a group.
3606 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3607 # @param AngleInRadians the angle of Rotation
3608 # @param NbOfSteps number of steps
3609 # @param Tolerance tolerance
3610 # @param MakeGroups forces the generation of new groups from existing ones
3611 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3612 # of all steps, else - size of each step
3613 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3614 # @ingroup l2_modif_extrurev
3615 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3616 MakeGroups=False, TotalAngle=False):
3617 if isinstance( theObject, Mesh ):
3618 theObject = theObject.GetMesh()
3619 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3620 Axis = self.smeshpyD.GetAxisStruct(Axis)
3621 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3622 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3623 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3624 self.mesh.SetParameters(Parameters)
3625 if TotalAngle and NbOfSteps:
3626 AngleInRadians /= NbOfSteps
3627 return self.editor.RotationSweepObjects([],[theObject],[theObject], Axis,
3628 AngleInRadians, NbOfSteps, Tolerance )
3630 ## Generates new elements by rotation of the elements of object around the axis
3631 # @param theObject object which elements should be sweeped.
3632 # It can be a mesh, a sub mesh or a group.
3633 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3634 # @param AngleInRadians the angle of Rotation
3635 # @param NbOfSteps number of steps
3636 # @param Tolerance tolerance
3637 # @param MakeGroups forces the generation of new groups from existing ones
3638 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3639 # of all steps, else - size of each step
3640 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3641 # @ingroup l2_modif_extrurev
3642 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3643 MakeGroups=False, TotalAngle=False):
3644 if isinstance( theObject, Mesh ):
3645 theObject = theObject.GetMesh()
3646 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3647 Axis = self.smeshpyD.GetAxisStruct(Axis)
3648 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3649 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3650 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3651 self.mesh.SetParameters(Parameters)
3652 if TotalAngle and NbOfSteps:
3653 AngleInRadians /= NbOfSteps
3654 return self.editor.RotationSweepObjects([],[theObject],[], Axis,
3655 AngleInRadians, NbOfSteps, Tolerance)
3657 ## Generates new elements by rotation of the elements of object around the axis
3658 # @param theObject object which elements should be sweeped.
3659 # It can be a mesh, a sub mesh or a group.
3660 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3661 # @param AngleInRadians the angle of Rotation
3662 # @param NbOfSteps number of steps
3663 # @param Tolerance tolerance
3664 # @param MakeGroups forces the generation of new groups from existing ones
3665 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3666 # of all steps, else - size of each step
3667 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3668 # @ingroup l2_modif_extrurev
3669 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3670 MakeGroups=False, TotalAngle=False):
3671 if isinstance( theObject, Mesh ):
3672 theObject = theObject.GetMesh()
3673 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3674 Axis = self.smeshpyD.GetAxisStruct(Axis)
3675 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3676 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3677 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3678 self.mesh.SetParameters(Parameters)
3679 if TotalAngle and NbOfSteps:
3680 AngleInRadians /= NbOfSteps
3681 return self.editor.RotationSweepObjects([],[],[theObject], Axis, AngleInRadians,
3682 NbOfSteps, Tolerance)
3684 ## Generates new elements by extrusion of the given elements and nodes
3685 # @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3686 # @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3687 # @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3688 # @param StepVector vector or DirStruct or 3 vector components, defining
3689 # the direction and value of extrusion for one step (the total extrusion
3690 # length will be NbOfSteps * ||StepVector||)
3691 # @param NbOfSteps the number of steps
3692 # @param MakeGroups forces the generation of new groups from existing ones
3693 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3694 # @ingroup l2_modif_extrurev
3695 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3696 unRegister = genObjUnRegister()
3697 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3698 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3699 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3701 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3702 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3703 if isinstance( StepVector, list ):
3704 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3706 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3707 Parameters = StepVector.PS.parameters + var_separator + Parameters
3708 self.mesh.SetParameters(Parameters)
3710 return self.editor.ExtrusionSweepObjects( nodes, edges, faces, StepVector, NbOfSteps, MakeGroups)
3713 ## Generates new elements by extrusion of the elements with given ids
3714 # @param IDsOfElements the list of elements ids for extrusion
3715 # @param StepVector vector or DirStruct or 3 vector components, defining
3716 # the direction and value of extrusion for one step (the total extrusion
3717 # length will be NbOfSteps * ||StepVector||)
3718 # @param NbOfSteps the number of steps
3719 # @param MakeGroups forces the generation of new groups from existing ones
3720 # @param IsNodes is True if elements with given ids are nodes
3721 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3722 # @ingroup l2_modif_extrurev
3723 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3724 if IDsOfElements == []:
3725 IDsOfElements = self.mesh
3726 unRegister = genObjUnRegister()
3727 if IDsOfElements and \
3728 isinstance( IDsOfElements, list ) and \
3729 isinstance( IDsOfElements[0], int ):
3730 IDsOfElements = self.GetIDSource( IDsOfElements, SMESH.ALL )
3731 unRegister.set( IDsOfElements )
3732 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3733 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3734 if isinstance( StepVector, list ):
3735 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3736 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3737 Parameters = StepVector.PS.parameters + var_separator + Parameters
3738 self.mesh.SetParameters(Parameters)
3740 if IsNodes: n = [IDsOfElements]
3741 else : e,f, = [IDsOfElements],[IDsOfElements]
3742 return self.editor.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3744 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3745 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3746 # Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3747 # @param StepSize length of one extrusion step (the total extrusion
3748 # length will be \a NbOfSteps * \a StepSize ).
3749 # @param NbOfSteps number of extrusion steps.
3750 # @param ByAverageNormal if True each node is translated by \a StepSize
3751 # along the average of the normal vectors to the faces sharing the node;
3752 # else each node is translated along the same average normal till
3753 # intersection with the plane got by translation of the face sharing
3754 # the node along its own normal by \a StepSize.
3755 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3756 # for every node of \a Elements.
3757 # @param MakeGroups forces generation of new groups from existing ones.
3758 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3759 # is not yet implemented. This parameter is used if \a Elements contains
3760 # both faces and edges, i.e. \a Elements is a Mesh.
3761 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3762 # empty list otherwise.
3763 # @ingroup l2_modif_extrurev
3764 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3765 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3766 unRegister = genObjUnRegister()
3767 if isinstance( Elements, Mesh ):
3768 Elements = [ Elements.GetMesh() ]
3769 if isinstance( Elements, list ):
3771 raise RuntimeError, "Elements empty!"
3772 if isinstance( Elements[0], int ):
3773 Elements = self.GetIDSource( Elements, SMESH.ALL )
3774 unRegister.set( Elements )
3776 Elements = [ Elements ]
3777 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3778 self.mesh.SetParameters(Parameters)
3779 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3780 UseInputElemsOnly, ByAverageNormal, MakeGroups, Dim)
3782 ## Generates new elements by extrusion of the elements which belong to the object
3783 # @param theObject the object which elements should be processed.
3784 # It can be a mesh, a sub mesh or a group.
3785 # @param StepVector vector or DirStruct or 3 vector components, defining
3786 # the direction and value of extrusion for one step (the total extrusion
3787 # length will be NbOfSteps * ||StepVector||)
3788 # @param NbOfSteps the number of steps
3789 # @param MakeGroups forces the generation of new groups from existing ones
3790 # @param IsNodes is True if elements to extrude are nodes
3791 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3792 # @ingroup l2_modif_extrurev
3793 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3794 if isinstance( theObject, Mesh ):
3795 theObject = theObject.GetMesh()
3796 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3797 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3798 if isinstance( StepVector, list ):
3799 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3800 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3801 Parameters = StepVector.PS.parameters + var_separator + Parameters
3802 self.mesh.SetParameters(Parameters)
3804 if IsNodes: n = [theObject]
3805 else : e,f, = [theObject],[theObject]
3806 return self.editor.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3808 ## Generates new elements by extrusion of the elements which belong to the object
3809 # @param theObject object which elements should be processed.
3810 # It can be a mesh, a sub mesh or a group.
3811 # @param StepVector vector or DirStruct or 3 vector components, defining
3812 # the direction and value of extrusion for one step (the total extrusion
3813 # length will be NbOfSteps * ||StepVector||)
3814 # @param NbOfSteps the number of steps
3815 # @param MakeGroups to generate new groups from existing ones
3816 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3817 # @ingroup l2_modif_extrurev
3818 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3819 if ( isinstance( theObject, Mesh )):
3820 theObject = theObject.GetMesh()
3821 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3822 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3823 if isinstance( StepVector, list ):
3824 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3825 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3826 Parameters = StepVector.PS.parameters + var_separator + Parameters
3827 self.mesh.SetParameters(Parameters)
3828 return self.editor.ExtrusionSweepObjects([],[theObject],[],
3829 StepVector, NbOfSteps, MakeGroups)
3831 ## Generates new elements by extrusion of the elements which belong to the object
3832 # @param theObject object which elements should be processed.
3833 # It can be a mesh, a sub mesh or a group.
3834 # @param StepVector vector or DirStruct or 3 vector components, defining
3835 # the direction and value of extrusion for one step (the total extrusion
3836 # length will be NbOfSteps * ||StepVector||)
3837 # @param NbOfSteps the number of steps
3838 # @param MakeGroups forces the generation of new groups from existing ones
3839 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3840 # @ingroup l2_modif_extrurev
3841 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3842 if ( isinstance( theObject, Mesh )):
3843 theObject = theObject.GetMesh()
3844 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3845 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3846 if isinstance( StepVector, list ):
3847 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3848 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3849 Parameters = StepVector.PS.parameters + var_separator + Parameters
3850 self.mesh.SetParameters(Parameters)
3851 return self.editor.ExtrusionSweepObjects([],[],[theObject],
3852 StepVector, NbOfSteps, MakeGroups)
3854 ## Generates new elements by extrusion of the elements with given ids
3855 # @param IDsOfElements is ids of elements
3856 # @param StepVector vector or DirStruct or 3 vector components, defining
3857 # the direction and value of extrusion for one step (the total extrusion
3858 # length will be NbOfSteps * ||StepVector||)
3859 # @param NbOfSteps the number of steps
3860 # @param ExtrFlags sets flags for extrusion
3861 # @param SewTolerance uses for comparing locations of nodes if flag
3862 # EXTRUSION_FLAG_SEW is set
3863 # @param MakeGroups forces the generation of new groups from existing ones
3864 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3865 # @ingroup l2_modif_extrurev
3866 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3867 ExtrFlags, SewTolerance, MakeGroups=False):
3868 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3869 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3870 if isinstance( StepVector, list ):
3871 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3872 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3873 ExtrFlags, SewTolerance, MakeGroups)
3875 ## Generates new elements by extrusion of the given elements and nodes along the path.
3876 # The path of extrusion must be a meshed edge.
3877 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3878 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3879 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3880 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3881 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3882 # contains not only path segments, else it can be None
3883 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3884 # @param HasAngles allows the shape to be rotated around the path
3885 # to get the resulting mesh in a helical fashion
3886 # @param Angles list of angles
3887 # @param HasRefPoint allows using the reference point
3888 # @param RefPoint the point around which the shape is rotated (the mass center of the
3889 # shape by default). The User can specify any point as the Reference Point.
3890 # @param MakeGroups forces the generation of new groups from existing ones
3891 # @param LinearVariation forces the computation of rotation angles as linear
3892 # variation of the given Angles along path steps
3893 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3894 # @ingroup l2_modif_extrurev
3895 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3896 NodeStart=1, HasAngles=False, Angles=[],
3897 HasRefPoint=False, RefPoint=[0,0,0],
3898 MakeGroups=False, LinearVariation=False):
3899 unRegister = genObjUnRegister()
3900 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3901 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3902 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3904 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3905 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3906 if isinstance( RefPoint, list ):
3907 RefPoint = SMESH.PointStruct( *RefPoint )
3908 if isinstance( PathMesh, Mesh ):
3909 PathMesh = PathMesh.GetMesh()
3910 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3911 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3912 self.mesh.SetParameters(Parameters)
3913 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3914 PathMesh, PathShape, NodeStart,
3915 HasAngles, Angles, LinearVariation,
3916 HasRefPoint, RefPoint, MakeGroups)
3918 ## Generates new elements by extrusion of the given elements
3919 # The path of extrusion must be a meshed edge.
3920 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3921 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3922 # @param NodeStart the start node from Path. Defines the direction of extrusion
3923 # @param HasAngles allows the shape to be rotated around the path
3924 # to get the resulting mesh in a helical fashion
3925 # @param Angles list of angles in radians
3926 # @param LinearVariation forces the computation of rotation angles as linear
3927 # variation of the given Angles along path steps
3928 # @param HasRefPoint allows using the reference point
3929 # @param RefPoint the point around which the elements are rotated (the mass
3930 # center of the elements by default).
3931 # The User can specify any point as the Reference Point.
3932 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3933 # @param MakeGroups forces the generation of new groups from existing ones
3934 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3935 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3936 # only SMESH::Extrusion_Error otherwise
3937 # @ingroup l2_modif_extrurev
3938 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3939 HasAngles, Angles, LinearVariation,
3940 HasRefPoint, RefPoint, MakeGroups, ElemType):
3941 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3942 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3944 elif isinstance( RefPoint, list ):
3945 RefPoint = PointStruct(*RefPoint)
3947 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3948 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3949 self.mesh.SetParameters(Parameters)
3951 if isinstance(Path, Mesh): Path = Path.GetMesh()
3953 unRegister = genObjUnRegister()
3954 if isinstance(Base, list):
3956 Base = self.GetIDSource( Base, ElemType )
3957 unRegister.set( Base )
3961 if isinstance(Base, Mesh):
3962 Base = Base.GetMesh()
3963 if isinstance(Base, SMESH._objref_SMESH_IDSource):
3965 if ElemType == SMESH.NODE: n = [Base]
3966 if ElemType == SMESH.EDGE: e = [Base]
3967 if ElemType == SMESH.FACE: f = [Base]
3968 gr,er = self.editor.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
3969 HasAngles, Angles, LinearVariation,
3970 HasRefPoint, RefPoint, MakeGroups)
3971 if MakeGroups: return gr,er
3974 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3977 ## Generates new elements by extrusion of the given elements
3978 # The path of extrusion must be a meshed edge.
3979 # @param IDsOfElements ids of elements
3980 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3981 # @param PathShape shape(edge) defines the sub-mesh for the path
3982 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3983 # @param HasAngles allows the shape to be rotated around the path
3984 # to get the resulting mesh in a helical fashion
3985 # @param Angles list of angles in radians
3986 # @param HasRefPoint allows using the reference point
3987 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3988 # The User can specify any point as the Reference Point.
3989 # @param MakeGroups forces the generation of new groups from existing ones
3990 # @param LinearVariation forces the computation of rotation angles as linear
3991 # variation of the given Angles along path steps
3992 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3993 # only SMESH::Extrusion_Error otherwise
3994 # @ingroup l2_modif_extrurev
3995 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3996 HasAngles, Angles, HasRefPoint, RefPoint,
3997 MakeGroups=False, LinearVariation=False):
3998 if IDsOfElements == []:
3999 IDsOfElements = self.GetElementsId()
4000 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4001 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4003 if isinstance( PathMesh, Mesh ):
4004 PathMesh = PathMesh.GetMesh()
4005 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4006 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4007 self.mesh.SetParameters(Parameters)
4008 n,e,f = [],[IDsOfElements],[IDsOfElements]
4009 gr,er = self.editor.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4010 NodeStart, HasAngles, Angles,
4012 HasRefPoint, RefPoint, MakeGroups)
4013 if MakeGroups: return gr,er
4016 ## Generates new elements by extrusion of the elements which belong to the object
4017 # The path of extrusion must be a meshed edge.
4018 # @param theObject the object which elements should be processed.
4019 # It can be a mesh, a sub-mesh or a group.
4020 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4021 # @param PathShape shape(edge) defines the sub-mesh for the path
4022 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4023 # @param HasAngles allows the shape to be rotated around the path
4024 # to get the resulting mesh in a helical fashion
4025 # @param Angles list of angles
4026 # @param HasRefPoint allows using the reference point
4027 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4028 # The User can specify any point as the Reference Point.
4029 # @param MakeGroups forces the generation of new groups from existing ones
4030 # @param LinearVariation forces the computation of rotation angles as linear
4031 # variation of the given Angles along path steps
4032 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4033 # only SMESH::Extrusion_Error otherwise
4034 # @ingroup l2_modif_extrurev
4035 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4036 HasAngles, Angles, HasRefPoint, RefPoint,
4037 MakeGroups=False, LinearVariation=False):
4038 if isinstance( theObject, Mesh ):
4039 theObject = theObject.GetMesh()
4040 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4041 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4042 if isinstance( PathMesh, Mesh ):
4043 PathMesh = PathMesh.GetMesh()
4044 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4045 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4046 self.mesh.SetParameters(Parameters)
4047 n,e,f = [],[theObject],[theObject]
4048 gr,er = self.editor.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4049 HasAngles, Angles, LinearVariation,
4050 HasRefPoint, RefPoint, MakeGroups)
4051 if MakeGroups: return gr,er
4054 ## Generates new elements by extrusion of the elements which belong to the object
4055 # The path of extrusion must be a meshed edge.
4056 # @param theObject the object which elements should be processed.
4057 # It can be a mesh, a sub mesh or a group.
4058 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4059 # @param PathShape shape(edge) defines the sub-mesh for the path
4060 # @param NodeStart the first or the last node on the edge. 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
4064 # @param HasRefPoint allows using the reference point
4065 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4066 # The User can specify any point as the Reference Point.
4067 # @param MakeGroups forces the generation of new groups from existing ones
4068 # @param LinearVariation forces the computation of rotation angles as linear
4069 # variation of the given Angles along path steps
4070 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4071 # only SMESH::Extrusion_Error otherwise
4072 # @ingroup l2_modif_extrurev
4073 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4074 HasAngles, Angles, HasRefPoint, RefPoint,
4075 MakeGroups=False, LinearVariation=False):
4076 if isinstance( theObject, Mesh ):
4077 theObject = theObject.GetMesh()
4078 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4079 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4080 if isinstance( PathMesh, Mesh ):
4081 PathMesh = PathMesh.GetMesh()
4082 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4083 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4084 self.mesh.SetParameters(Parameters)
4085 n,e,f = [],[theObject],[]
4086 gr,er = self.editor.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4087 HasAngles, Angles, LinearVariation,
4088 HasRefPoint, RefPoint, MakeGroups)
4089 if MakeGroups: return gr,er
4092 ## Generates new elements by extrusion of the elements which belong to the object
4093 # The path of extrusion must be a meshed edge.
4094 # @param theObject the object which elements should be processed.
4095 # It can be a mesh, a sub mesh or a group.
4096 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4097 # @param PathShape shape(edge) defines the sub-mesh for the path
4098 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4099 # @param HasAngles allows the shape to be rotated around the path
4100 # to get the resulting mesh in a helical fashion
4101 # @param Angles list of angles
4102 # @param HasRefPoint allows using the reference point
4103 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4104 # The User can specify any point as the Reference Point.
4105 # @param MakeGroups forces the generation of new groups from existing ones
4106 # @param LinearVariation forces the computation of rotation angles as linear
4107 # variation of the given Angles along path steps
4108 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4109 # only SMESH::Extrusion_Error otherwise
4110 # @ingroup l2_modif_extrurev
4111 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4112 HasAngles, Angles, HasRefPoint, RefPoint,
4113 MakeGroups=False, LinearVariation=False):
4114 if ( isinstance( theObject, Mesh )):
4115 theObject = theObject.GetMesh()
4116 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
4117 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4118 if ( isinstance( PathMesh, Mesh )):
4119 PathMesh = PathMesh.GetMesh()
4120 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4121 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4122 self.mesh.SetParameters(Parameters)
4123 n,e,f = [],[],[theObject]
4124 gr,er = self.editor.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4125 HasAngles, Angles, LinearVariation,
4126 HasRefPoint, RefPoint, MakeGroups)
4127 if MakeGroups: return gr,er
4130 ## Creates a symmetrical copy of mesh elements
4131 # @param IDsOfElements list of elements ids
4132 # @param Mirror is AxisStruct or geom object(point, line, plane)
4133 # @param theMirrorType is POINT, AXIS or PLANE
4134 # If the Mirror is a geom object this parameter is unnecessary
4135 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4136 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4137 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4138 # @ingroup l2_modif_trsf
4139 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4140 if IDsOfElements == []:
4141 IDsOfElements = self.GetElementsId()
4142 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4143 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4144 theMirrorType = Mirror._mirrorType
4146 self.mesh.SetParameters(Mirror.parameters)
4147 if Copy and MakeGroups:
4148 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4149 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4152 ## Creates a new mesh by a symmetrical copy of mesh elements
4153 # @param IDsOfElements the list of elements ids
4154 # @param Mirror is AxisStruct or geom object (point, line, plane)
4155 # @param theMirrorType is POINT, AXIS or PLANE
4156 # If the Mirror is a geom object this parameter is unnecessary
4157 # @param MakeGroups to generate new groups from existing ones
4158 # @param NewMeshName a name of the new mesh to create
4159 # @return instance of Mesh class
4160 # @ingroup l2_modif_trsf
4161 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4162 if IDsOfElements == []:
4163 IDsOfElements = self.GetElementsId()
4164 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4165 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4166 theMirrorType = Mirror._mirrorType
4168 self.mesh.SetParameters(Mirror.parameters)
4169 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4170 MakeGroups, NewMeshName)
4171 return Mesh(self.smeshpyD,self.geompyD,mesh)
4173 ## Creates a symmetrical copy of the object
4174 # @param theObject mesh, submesh or group
4175 # @param Mirror AxisStruct or geom object (point, line, plane)
4176 # @param theMirrorType is POINT, AXIS or PLANE
4177 # If the Mirror is a geom object this parameter is unnecessary
4178 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4179 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4180 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4181 # @ingroup l2_modif_trsf
4182 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4183 if ( isinstance( theObject, Mesh )):
4184 theObject = theObject.GetMesh()
4185 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4186 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4187 theMirrorType = Mirror._mirrorType
4189 self.mesh.SetParameters(Mirror.parameters)
4190 if Copy and MakeGroups:
4191 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4192 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4195 ## Creates a new mesh by a symmetrical copy of the object
4196 # @param theObject mesh, submesh or group
4197 # @param Mirror AxisStruct or geom object (point, line, plane)
4198 # @param theMirrorType POINT, AXIS or PLANE
4199 # If the Mirror is a geom object this parameter is unnecessary
4200 # @param MakeGroups forces the generation of new groups from existing ones
4201 # @param NewMeshName the name of the new mesh to create
4202 # @return instance of Mesh class
4203 # @ingroup l2_modif_trsf
4204 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4205 if ( isinstance( theObject, Mesh )):
4206 theObject = theObject.GetMesh()
4207 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4208 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4209 theMirrorType = Mirror._mirrorType
4211 self.mesh.SetParameters(Mirror.parameters)
4212 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4213 MakeGroups, NewMeshName)
4214 return Mesh( self.smeshpyD,self.geompyD,mesh )
4216 ## Translates the elements
4217 # @param IDsOfElements list of elements ids
4218 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4219 # @param Copy allows copying the translated elements
4220 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4221 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4222 # @ingroup l2_modif_trsf
4223 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4224 if IDsOfElements == []:
4225 IDsOfElements = self.GetElementsId()
4226 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4227 Vector = self.smeshpyD.GetDirStruct(Vector)
4228 if isinstance( Vector, list ):
4229 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4230 self.mesh.SetParameters(Vector.PS.parameters)
4231 if Copy and MakeGroups:
4232 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4233 self.editor.Translate(IDsOfElements, Vector, Copy)
4236 ## Creates a new mesh of translated elements
4237 # @param IDsOfElements list of elements ids
4238 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4239 # @param MakeGroups forces the generation of new groups from existing ones
4240 # @param NewMeshName the name of the newly created mesh
4241 # @return instance of Mesh class
4242 # @ingroup l2_modif_trsf
4243 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4244 if IDsOfElements == []:
4245 IDsOfElements = self.GetElementsId()
4246 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4247 Vector = self.smeshpyD.GetDirStruct(Vector)
4248 if isinstance( Vector, list ):
4249 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4250 self.mesh.SetParameters(Vector.PS.parameters)
4251 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4252 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4254 ## Translates the object
4255 # @param theObject the object to translate (mesh, submesh, or group)
4256 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4257 # @param Copy allows copying the translated elements
4258 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4259 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4260 # @ingroup l2_modif_trsf
4261 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4262 if ( isinstance( theObject, Mesh )):
4263 theObject = theObject.GetMesh()
4264 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4265 Vector = self.smeshpyD.GetDirStruct(Vector)
4266 if isinstance( Vector, list ):
4267 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4268 self.mesh.SetParameters(Vector.PS.parameters)
4269 if Copy and MakeGroups:
4270 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4271 self.editor.TranslateObject(theObject, Vector, Copy)
4274 ## Creates a new mesh from the translated object
4275 # @param theObject the object to translate (mesh, submesh, or group)
4276 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4277 # @param MakeGroups forces the generation of new groups from existing ones
4278 # @param NewMeshName the name of the newly created mesh
4279 # @return instance of Mesh class
4280 # @ingroup l2_modif_trsf
4281 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4282 if isinstance( theObject, Mesh ):
4283 theObject = theObject.GetMesh()
4284 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4285 Vector = self.smeshpyD.GetDirStruct(Vector)
4286 if isinstance( Vector, list ):
4287 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4288 self.mesh.SetParameters(Vector.PS.parameters)
4289 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4290 return Mesh( self.smeshpyD, self.geompyD, mesh )
4294 ## Scales the object
4295 # @param theObject - the object to translate (mesh, submesh, or group)
4296 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4297 # @param theScaleFact - list of 1-3 scale factors for axises
4298 # @param Copy - allows copying the translated elements
4299 # @param MakeGroups - forces the generation of new groups from existing
4301 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4302 # empty list otherwise
4303 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4304 unRegister = genObjUnRegister()
4305 if ( isinstance( theObject, Mesh )):
4306 theObject = theObject.GetMesh()
4307 if ( isinstance( theObject, list )):
4308 theObject = self.GetIDSource(theObject, SMESH.ALL)
4309 unRegister.set( theObject )
4310 if ( isinstance( thePoint, list )):
4311 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4312 if ( isinstance( theScaleFact, float )):
4313 theScaleFact = [theScaleFact]
4314 if ( isinstance( theScaleFact, int )):
4315 theScaleFact = [ float(theScaleFact)]
4317 self.mesh.SetParameters(thePoint.parameters)
4319 if Copy and MakeGroups:
4320 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4321 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4324 ## Creates a new mesh from the translated object
4325 # @param theObject - the object to translate (mesh, submesh, or group)
4326 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4327 # @param theScaleFact - list of 1-3 scale factors for axises
4328 # @param MakeGroups - forces the generation of new groups from existing ones
4329 # @param NewMeshName - the name of the newly created mesh
4330 # @return instance of Mesh class
4331 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4332 unRegister = genObjUnRegister()
4333 if (isinstance(theObject, Mesh)):
4334 theObject = theObject.GetMesh()
4335 if ( isinstance( theObject, list )):
4336 theObject = self.GetIDSource(theObject,SMESH.ALL)
4337 unRegister.set( theObject )
4338 if ( isinstance( thePoint, list )):
4339 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4340 if ( isinstance( theScaleFact, float )):
4341 theScaleFact = [theScaleFact]
4342 if ( isinstance( theScaleFact, int )):
4343 theScaleFact = [ float(theScaleFact)]
4345 self.mesh.SetParameters(thePoint.parameters)
4346 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4347 MakeGroups, NewMeshName)
4348 return Mesh( self.smeshpyD, self.geompyD, mesh )
4352 ## Rotates the elements
4353 # @param IDsOfElements list of elements ids
4354 # @param Axis the axis of rotation (AxisStruct or geom line)
4355 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4356 # @param Copy allows copying the rotated elements
4357 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4358 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4359 # @ingroup l2_modif_trsf
4360 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4361 if IDsOfElements == []:
4362 IDsOfElements = self.GetElementsId()
4363 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4364 Axis = self.smeshpyD.GetAxisStruct(Axis)
4365 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4366 Parameters = Axis.parameters + var_separator + Parameters
4367 self.mesh.SetParameters(Parameters)
4368 if Copy and MakeGroups:
4369 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4370 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4373 ## Creates a new mesh of rotated elements
4374 # @param IDsOfElements list of element ids
4375 # @param Axis the axis of rotation (AxisStruct or geom line)
4376 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4377 # @param MakeGroups forces the generation of new groups from existing ones
4378 # @param NewMeshName the name of the newly created mesh
4379 # @return instance of Mesh class
4380 # @ingroup l2_modif_trsf
4381 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4382 if IDsOfElements == []:
4383 IDsOfElements = self.GetElementsId()
4384 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4385 Axis = self.smeshpyD.GetAxisStruct(Axis)
4386 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4387 Parameters = Axis.parameters + var_separator + Parameters
4388 self.mesh.SetParameters(Parameters)
4389 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4390 MakeGroups, NewMeshName)
4391 return Mesh( self.smeshpyD, self.geompyD, mesh )
4393 ## Rotates the object
4394 # @param theObject the object to rotate( mesh, submesh, or group)
4395 # @param Axis the axis of rotation (AxisStruct or geom line)
4396 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4397 # @param Copy allows copying the rotated elements
4398 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4399 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4400 # @ingroup l2_modif_trsf
4401 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4402 if (isinstance(theObject, Mesh)):
4403 theObject = theObject.GetMesh()
4404 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4405 Axis = self.smeshpyD.GetAxisStruct(Axis)
4406 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4407 Parameters = Axis.parameters + ":" + Parameters
4408 self.mesh.SetParameters(Parameters)
4409 if Copy and MakeGroups:
4410 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4411 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4414 ## Creates a new mesh from the rotated object
4415 # @param theObject the object to rotate (mesh, submesh, or group)
4416 # @param Axis the axis of rotation (AxisStruct or geom line)
4417 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4418 # @param MakeGroups forces the generation of new groups from existing ones
4419 # @param NewMeshName the name of the newly created mesh
4420 # @return instance of Mesh class
4421 # @ingroup l2_modif_trsf
4422 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4423 if (isinstance( theObject, Mesh )):
4424 theObject = theObject.GetMesh()
4425 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4426 Axis = self.smeshpyD.GetAxisStruct(Axis)
4427 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4428 Parameters = Axis.parameters + ":" + Parameters
4429 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4430 MakeGroups, NewMeshName)
4431 self.mesh.SetParameters(Parameters)
4432 return Mesh( self.smeshpyD, self.geompyD, mesh )
4434 ## Finds groups of adjacent nodes within Tolerance.
4435 # @param Tolerance the value of tolerance
4436 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4437 # @ingroup l2_modif_trsf
4438 def FindCoincidentNodes (self, Tolerance):
4439 return self.editor.FindCoincidentNodes(Tolerance)
4441 ## Finds groups of ajacent nodes within Tolerance.
4442 # @param Tolerance the value of tolerance
4443 # @param SubMeshOrGroup SubMesh or Group
4444 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4445 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4446 # @ingroup l2_modif_trsf
4447 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4448 unRegister = genObjUnRegister()
4449 if (isinstance( SubMeshOrGroup, Mesh )):
4450 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4451 if not isinstance( exceptNodes, list):
4452 exceptNodes = [ exceptNodes ]
4453 if exceptNodes and isinstance( exceptNodes[0], int):
4454 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4455 unRegister.set( exceptNodes )
4456 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4459 # @param GroupsOfNodes a list of pairs of nodes IDs for merging
4460 # (e.g. [[1,12],[25,4]], then nodes 12 and 4 will be removed and replaced
4461 # by nodes 1 and 25 correspondingly in all elements and groups
4462 # @ingroup l2_modif_trsf
4463 def MergeNodes (self, GroupsOfNodes):
4464 self.editor.MergeNodes(GroupsOfNodes)
4466 ## Finds the elements built on the same nodes.
4467 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4468 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4469 # @ingroup l2_modif_trsf
4470 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4471 if not MeshOrSubMeshOrGroup:
4472 MeshOrSubMeshOrGroup=self.mesh
4473 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4474 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4475 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4477 ## Merges elements in each given group.
4478 # @param GroupsOfElementsID a list of pairs of elements IDs for merging
4479 # (e.g. [[1,12],[25,4]], then elements 12 and 4 will be removed and
4480 # replaced by elements 1 and 25 in all groups)
4481 # @ingroup l2_modif_trsf
4482 def MergeElements(self, GroupsOfElementsID):
4483 self.editor.MergeElements(GroupsOfElementsID)
4485 ## Leaves one element and removes all other elements built on the same nodes.
4486 # @ingroup l2_modif_trsf
4487 def MergeEqualElements(self):
4488 self.editor.MergeEqualElements()
4490 ## Sews free borders
4491 # @return SMESH::Sew_Error
4492 # @ingroup l2_modif_trsf
4493 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4494 FirstNodeID2, SecondNodeID2, LastNodeID2,
4495 CreatePolygons, CreatePolyedrs):
4496 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4497 FirstNodeID2, SecondNodeID2, LastNodeID2,
4498 CreatePolygons, CreatePolyedrs)
4500 ## Sews conform free borders
4501 # @return SMESH::Sew_Error
4502 # @ingroup l2_modif_trsf
4503 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4504 FirstNodeID2, SecondNodeID2):
4505 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4506 FirstNodeID2, SecondNodeID2)
4508 ## Sews border to side
4509 # @return SMESH::Sew_Error
4510 # @ingroup l2_modif_trsf
4511 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4512 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4513 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4514 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4516 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4517 # merged with the nodes of elements of Side2.
4518 # The number of elements in theSide1 and in theSide2 must be
4519 # equal and they should have similar nodal connectivity.
4520 # The nodes to merge should belong to side borders and
4521 # the first node should be linked to the second.
4522 # @return SMESH::Sew_Error
4523 # @ingroup l2_modif_trsf
4524 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4525 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4526 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4527 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4528 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4529 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4531 ## Sets new nodes for the given element.
4532 # @param ide the element id
4533 # @param newIDs nodes ids
4534 # @return If the number of nodes does not correspond to the type of element - returns false
4535 # @ingroup l2_modif_edit
4536 def ChangeElemNodes(self, ide, newIDs):
4537 return self.editor.ChangeElemNodes(ide, newIDs)
4539 ## If during the last operation of MeshEditor some nodes were
4540 # created, this method returns the list of their IDs, \n
4541 # if new nodes were not created - returns empty list
4542 # @return the list of integer values (can be empty)
4543 # @ingroup l1_auxiliary
4544 def GetLastCreatedNodes(self):
4545 return self.editor.GetLastCreatedNodes()
4547 ## If during the last operation of MeshEditor some elements were
4548 # created this method returns the list of their IDs, \n
4549 # if new elements were not created - returns empty list
4550 # @return the list of integer values (can be empty)
4551 # @ingroup l1_auxiliary
4552 def GetLastCreatedElems(self):
4553 return self.editor.GetLastCreatedElems()
4555 ## Clears sequences of nodes and elements created by mesh edition oparations
4556 # @ingroup l1_auxiliary
4557 def ClearLastCreated(self):
4558 self.editor.ClearLastCreated()
4560 ## Creates Duplicates given elements, i.e. creates new elements based on the
4561 # same nodes as the given ones.
4562 # @param theElements - container of elements to duplicate. It can be a Mesh,
4563 # sub-mesh, group, filter or a list of element IDs.
4564 # @param theGroupName - a name of group to contain the generated elements.
4565 # If a group with such a name already exists, the new elements
4566 # are added to the existng group, else a new group is created.
4567 # If \a theGroupName is empty, new elements are not added
4569 # @return a group where the new elements are added. None if theGroupName == "".
4570 # @ingroup l2_modif_edit
4571 def DoubleElements(self, theElements, theGroupName=""):
4572 unRegister = genObjUnRegister()
4573 if isinstance( theElements, Mesh ):
4574 theElements = theElements.mesh
4575 elif isinstance( theElements, list ):
4576 theElements = self.GetIDSource( theElements, SMESH.ALL )
4577 unRegister.set( theElements )
4578 return self.editor.DoubleElements(theElements, theGroupName)
4580 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4581 # @param theNodes identifiers of nodes to be doubled
4582 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4583 # nodes. If list of element identifiers is empty then nodes are doubled but
4584 # they not assigned to elements
4585 # @return TRUE if operation has been completed successfully, FALSE otherwise
4586 # @ingroup l2_modif_edit
4587 def DoubleNodes(self, theNodes, theModifiedElems):
4588 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4590 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4591 # This method provided for convenience works as DoubleNodes() described above.
4592 # @param theNodeId identifiers of node to be doubled
4593 # @param theModifiedElems identifiers of elements to be updated
4594 # @return TRUE if operation has been completed successfully, FALSE otherwise
4595 # @ingroup l2_modif_edit
4596 def DoubleNode(self, theNodeId, theModifiedElems):
4597 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4599 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4600 # This method provided for convenience works as DoubleNodes() described above.
4601 # @param theNodes group of nodes to be doubled
4602 # @param theModifiedElems group of elements to be updated.
4603 # @param theMakeGroup forces the generation of a group containing new nodes.
4604 # @return TRUE or a created group if operation has been completed successfully,
4605 # FALSE or None otherwise
4606 # @ingroup l2_modif_edit
4607 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4609 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4610 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4612 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4613 # This method provided for convenience works as DoubleNodes() described above.
4614 # @param theNodes list of groups of nodes to be doubled
4615 # @param theModifiedElems list of groups of elements to be updated.
4616 # @param theMakeGroup forces the generation of a group containing new nodes.
4617 # @return TRUE if operation has been completed successfully, FALSE otherwise
4618 # @ingroup l2_modif_edit
4619 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4621 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4622 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4624 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4625 # @param theElems - the list of elements (edges or faces) to be replicated
4626 # The nodes for duplication could be found from these elements
4627 # @param theNodesNot - list of nodes to NOT replicate
4628 # @param theAffectedElems - the list of elements (cells and edges) to which the
4629 # replicated nodes should be associated to.
4630 # @return TRUE if operation has been completed successfully, FALSE otherwise
4631 # @ingroup l2_modif_edit
4632 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4633 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4635 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4636 # @param theElems - the list of elements (edges or faces) to be replicated
4637 # The nodes for duplication could be found from these elements
4638 # @param theNodesNot - list of nodes to NOT replicate
4639 # @param theShape - shape to detect affected elements (element which geometric center
4640 # located on or inside shape).
4641 # The replicated nodes should be associated to affected elements.
4642 # @return TRUE if operation has been completed successfully, FALSE otherwise
4643 # @ingroup l2_modif_edit
4644 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4645 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4647 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4648 # This method provided for convenience works as DoubleNodes() described above.
4649 # @param theElems - group of of elements (edges or faces) to be replicated
4650 # @param theNodesNot - group of nodes not to replicated
4651 # @param theAffectedElems - group of elements to which the replicated nodes
4652 # should be associated to.
4653 # @param theMakeGroup forces the generation of a group containing new elements.
4654 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4655 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4656 # FALSE or None otherwise
4657 # @ingroup l2_modif_edit
4658 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4659 theMakeGroup=False, theMakeNodeGroup=False):
4660 if theMakeGroup or theMakeNodeGroup:
4661 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4663 theMakeGroup, theMakeNodeGroup)
4664 if theMakeGroup and theMakeNodeGroup:
4667 return twoGroups[ int(theMakeNodeGroup) ]
4668 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4670 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4671 # This method provided for convenience works as DoubleNodes() described above.
4672 # @param theElems - group of of elements (edges or faces) to be replicated
4673 # @param theNodesNot - group of nodes not to replicated
4674 # @param theShape - shape to detect affected elements (element which geometric center
4675 # located on or inside shape).
4676 # The replicated nodes should be associated to affected elements.
4677 # @ingroup l2_modif_edit
4678 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4679 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4681 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4682 # This method provided for convenience works as DoubleNodes() described above.
4683 # @param theElems - list of groups of elements (edges or faces) to be replicated
4684 # @param theNodesNot - list of groups of nodes not to replicated
4685 # @param theAffectedElems - group of elements to which the replicated nodes
4686 # should be associated to.
4687 # @param theMakeGroup forces the generation of a group containing new elements.
4688 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4689 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4690 # FALSE or None otherwise
4691 # @ingroup l2_modif_edit
4692 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4693 theMakeGroup=False, theMakeNodeGroup=False):
4694 if theMakeGroup or theMakeNodeGroup:
4695 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4697 theMakeGroup, theMakeNodeGroup)
4698 if theMakeGroup and theMakeNodeGroup:
4701 return twoGroups[ int(theMakeNodeGroup) ]
4702 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4704 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4705 # This method provided for convenience works as DoubleNodes() described above.
4706 # @param theElems - list of groups of elements (edges or faces) to be replicated
4707 # @param theNodesNot - list of groups of nodes not to replicated
4708 # @param theShape - shape to detect affected elements (element which geometric center
4709 # located on or inside shape).
4710 # The replicated nodes should be associated to affected elements.
4711 # @return TRUE if operation has been completed successfully, FALSE otherwise
4712 # @ingroup l2_modif_edit
4713 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4714 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4716 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4717 # This method is the first step of DoubleNodeElemGroupsInRegion.
4718 # @param theElems - list of groups of elements (edges or faces) to be replicated
4719 # @param theNodesNot - list of groups of nodes not to replicated
4720 # @param theShape - shape to detect affected elements (element which geometric center
4721 # located on or inside shape).
4722 # The replicated nodes should be associated to affected elements.
4723 # @return groups of affected elements
4724 # @ingroup l2_modif_edit
4725 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4726 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4728 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4729 # The list of groups must describe a partition of the mesh volumes.
4730 # The nodes of the internal faces at the boundaries of the groups are doubled.
4731 # In option, the internal faces are replaced by flat elements.
4732 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4733 # @param theDomains - list of groups of volumes
4734 # @param createJointElems - if TRUE, create the elements
4735 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4736 # the boundary between \a theDomains and the rest mesh
4737 # @return TRUE if operation has been completed successfully, FALSE otherwise
4738 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4739 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4741 ## Double nodes on some external faces and create flat elements.
4742 # Flat elements are mainly used by some types of mechanic calculations.
4744 # Each group of the list must be constituted of faces.
4745 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4746 # @param theGroupsOfFaces - list of groups of faces
4747 # @return TRUE if operation has been completed successfully, FALSE otherwise
4748 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4749 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4751 ## identify all the elements around a geom shape, get the faces delimiting the hole
4753 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4754 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4756 def _getFunctor(self, funcType ):
4757 fn = self.functors[ funcType._v ]
4759 fn = self.smeshpyD.GetFunctor(funcType)
4760 fn.SetMesh(self.mesh)
4761 self.functors[ funcType._v ] = fn
4764 def _valueFromFunctor(self, funcType, elemId):
4765 fn = self._getFunctor( funcType )
4766 if fn.GetElementType() == self.GetElementType(elemId, True):
4767 val = fn.GetValue(elemId)
4772 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4773 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4774 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4775 # @ingroup l1_measurements
4776 def GetLength(self, elemId=None):
4779 length = self.smeshpyD.GetLength(self)
4781 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4784 ## Get area of 2D element or sum of areas of all 2D mesh elements
4785 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4786 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4787 # @ingroup l1_measurements
4788 def GetArea(self, elemId=None):
4791 area = self.smeshpyD.GetArea(self)
4793 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4796 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4797 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4798 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4799 # @ingroup l1_measurements
4800 def GetVolume(self, elemId=None):
4803 volume = self.smeshpyD.GetVolume(self)
4805 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4808 ## Get maximum element length.
4809 # @param elemId mesh element ID
4810 # @return element's maximum length value
4811 # @ingroup l1_measurements
4812 def GetMaxElementLength(self, elemId):
4813 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4814 ftype = SMESH.FT_MaxElementLength3D
4816 ftype = SMESH.FT_MaxElementLength2D
4817 return self._valueFromFunctor(ftype, elemId)
4819 ## Get aspect ratio of 2D or 3D element.
4820 # @param elemId mesh element ID
4821 # @return element's aspect ratio value
4822 # @ingroup l1_measurements
4823 def GetAspectRatio(self, elemId):
4824 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4825 ftype = SMESH.FT_AspectRatio3D
4827 ftype = SMESH.FT_AspectRatio
4828 return self._valueFromFunctor(ftype, elemId)
4830 ## Get warping angle of 2D element.
4831 # @param elemId mesh element ID
4832 # @return element's warping angle value
4833 # @ingroup l1_measurements
4834 def GetWarping(self, elemId):
4835 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4837 ## Get minimum angle of 2D element.
4838 # @param elemId mesh element ID
4839 # @return element's minimum angle value
4840 # @ingroup l1_measurements
4841 def GetMinimumAngle(self, elemId):
4842 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4844 ## Get taper of 2D element.
4845 # @param elemId mesh element ID
4846 # @return element's taper value
4847 # @ingroup l1_measurements
4848 def GetTaper(self, elemId):
4849 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4851 ## Get skew of 2D element.
4852 # @param elemId mesh element ID
4853 # @return element's skew value
4854 # @ingroup l1_measurements
4855 def GetSkew(self, elemId):
4856 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4858 ## Return minimal and maximal value of a given functor.
4859 # @param funType a functor type, an item of SMESH.FunctorType enum
4860 # (one of SMESH.FunctorType._items)
4861 # @param meshPart a part of mesh (group, sub-mesh) to treat
4862 # @return tuple (min,max)
4863 # @ingroup l1_measurements
4864 def GetMinMax(self, funType, meshPart=None):
4865 unRegister = genObjUnRegister()
4866 if isinstance( meshPart, list ):
4867 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4868 unRegister.set( meshPart )
4869 if isinstance( meshPart, Mesh ):
4870 meshPart = meshPart.mesh
4871 fun = self._getFunctor( funType )
4874 hist = fun.GetLocalHistogram( 1, False, meshPart )
4876 hist = fun.GetHistogram( 1, False )
4878 return hist[0].min, hist[0].max
4881 pass # end of Mesh class
4883 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4885 class Pattern(SMESH._objref_SMESH_Pattern):
4887 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4888 decrFun = lambda i: i-1
4889 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4890 theMesh.SetParameters(Parameters)
4891 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4893 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4894 decrFun = lambda i: i-1
4895 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4896 theMesh.SetParameters(Parameters)
4897 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4899 # Registering the new proxy for Pattern
4900 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4902 ## Private class used to bind methods creating algorithms to the class Mesh
4907 self.defaultAlgoType = ""
4908 self.algoTypeToClass = {}
4910 # Stores a python class of algorithm
4911 def add(self, algoClass):
4912 if type( algoClass ).__name__ == 'classobj' and \
4913 hasattr( algoClass, "algoType"):
4914 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4915 if not self.defaultAlgoType and \
4916 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4917 self.defaultAlgoType = algoClass.algoType
4918 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4920 # creates a copy of self and assign mesh to the copy
4921 def copy(self, mesh):
4922 other = algoCreator()
4923 other.defaultAlgoType = self.defaultAlgoType
4924 other.algoTypeToClass = self.algoTypeToClass
4928 # creates an instance of algorithm
4929 def __call__(self,algo="",geom=0,*args):
4930 algoType = self.defaultAlgoType
4931 for arg in args + (algo,geom):
4932 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4934 if isinstance( arg, str ) and arg:
4936 if not algoType and self.algoTypeToClass:
4937 algoType = self.algoTypeToClass.keys()[0]
4938 if self.algoTypeToClass.has_key( algoType ):
4939 #print "Create algo",algoType
4940 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4941 raise RuntimeError, "No class found for algo type %s" % algoType
4944 # Private class used to substitute and store variable parameters of hypotheses.
4946 class hypMethodWrapper:
4947 def __init__(self, hyp, method):
4949 self.method = method
4950 #print "REBIND:", method.__name__
4953 # call a method of hypothesis with calling SetVarParameter() before
4954 def __call__(self,*args):
4956 return self.method( self.hyp, *args ) # hypothesis method with no args
4958 #print "MethWrapper.__call__",self.method.__name__, args
4960 parsed = ParseParameters(*args) # replace variables with their values
4961 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4962 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4963 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4964 # maybe there is a replaced string arg which is not variable
4965 result = self.method( self.hyp, *args )
4966 except ValueError, detail: # raised by ParseParameters()
4968 result = self.method( self.hyp, *args )
4969 except omniORB.CORBA.BAD_PARAM:
4970 raise ValueError, detail # wrong variable name
4975 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4976 class genObjUnRegister:
4978 def __init__(self, genObj=None):
4979 self.genObjList = []
4983 def set(self, genObj):
4984 "Store one or a list of of SALOME.GenericObj'es"
4985 if isinstance( genObj, list ):
4986 self.genObjList.extend( genObj )
4988 self.genObjList.append( genObj )
4992 for genObj in self.genObjList:
4993 if genObj and hasattr( genObj, "UnRegister" ):
4996 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4998 #print "pluginName: ", pluginName
4999 pluginBuilderName = pluginName + "Builder"
5001 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5002 except Exception, e:
5003 from salome_utils import verbose
5004 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5006 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5007 plugin = eval( pluginBuilderName )
5008 #print " plugin:" , str(plugin)
5010 # add methods creating algorithms to Mesh
5011 for k in dir( plugin ):
5012 if k[0] == '_': continue
5013 algo = getattr( plugin, k )
5014 #print " algo:", str(algo)
5015 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5016 #print " meshMethod:" , str(algo.meshMethod)
5017 if not hasattr( Mesh, algo.meshMethod ):
5018 setattr( Mesh, algo.meshMethod, algoCreator() )
5020 getattr( Mesh, algo.meshMethod ).add( algo )