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 # Check 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 raise TypeError, "The Threshold should be a shape."
749 if isinstance(UnaryOp,float):
750 aCriterion.Tolerance = UnaryOp
751 UnaryOp = FT_Undefined
753 elif CritType == FT_BelongToMeshGroup:
754 # Check that Threshold is a group
755 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
756 if aThreshold.GetType() != elementType:
757 raise ValueError, "Group type mismatches Element type"
758 aCriterion.ThresholdStr = aThreshold.GetName()
759 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
761 raise TypeError, "The Threshold should be a Mesh Group"
762 elif CritType == FT_RangeOfIds:
763 # Check that Threshold is string
764 if isinstance(aThreshold, str):
765 aCriterion.ThresholdStr = aThreshold
767 raise TypeError, "The Threshold should be a string."
768 elif CritType == FT_CoplanarFaces:
769 # Check the Threshold
770 if isinstance(aThreshold, int):
771 aCriterion.ThresholdID = str(aThreshold)
772 elif isinstance(aThreshold, str):
775 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
776 aCriterion.ThresholdID = aThreshold
779 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
780 elif CritType == FT_ConnectedElements:
781 # Check the Threshold
782 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
783 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
784 if not aCriterion.ThresholdID:
785 name = aThreshold.GetName()
787 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
788 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
789 elif isinstance(aThreshold, int): # node id
790 aCriterion.Threshold = aThreshold
791 elif isinstance(aThreshold, list): # 3 point coordinates
792 if len( aThreshold ) < 3:
793 raise ValueError, "too few point coordinates, must be 3"
794 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
795 elif isinstance(aThreshold, str):
796 if aThreshold.isdigit():
797 aCriterion.Threshold = aThreshold # node id
799 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
802 "The Threshold should either a VERTEX, or a node ID, "\
803 "or a list of point coordinates and not '%s'"%aThreshold
804 elif CritType == FT_ElemGeomType:
805 # Check the Threshold
807 aCriterion.Threshold = self.EnumToLong(aThreshold)
808 assert( aThreshold in SMESH.GeometryType._items )
810 if isinstance(aThreshold, int):
811 aCriterion.Threshold = aThreshold
813 raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
816 elif CritType == FT_EntityType:
817 # Check the Threshold
819 aCriterion.Threshold = self.EnumToLong(aThreshold)
820 assert( aThreshold in SMESH.EntityType._items )
822 if isinstance(aThreshold, int):
823 aCriterion.Threshold = aThreshold
825 raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
829 elif CritType == FT_GroupColor:
830 # Check the Threshold
832 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
834 raise TypeError, "The threshold value should be of SALOMEDS.Color type"
836 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
837 FT_LinearOrQuadratic, FT_BadOrientedVolume,
838 FT_BareBorderFace, FT_BareBorderVolume,
839 FT_OverConstrainedFace, FT_OverConstrainedVolume,
840 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
841 # At this point the Threshold is unnecessary
842 if aThreshold == FT_LogicalNOT:
843 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
844 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
845 aCriterion.BinaryOp = aThreshold
849 aThreshold = float(aThreshold)
850 aCriterion.Threshold = aThreshold
852 raise TypeError, "The Threshold should be a number."
855 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
856 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
858 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
859 aCriterion.BinaryOp = self.EnumToLong(Threshold)
861 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
862 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
864 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
865 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
869 ## Creates a filter with the given parameters
870 # @param elementType the type of elements in the group
871 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
872 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
873 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
874 # @param UnaryOp FT_LogicalNOT or FT_Undefined
875 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
876 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
877 # @param mesh the mesh to initialize the filter with
878 # @return SMESH_Filter
880 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
881 # @ingroup l1_controls
882 def GetFilter(self,elementType,
883 CritType=FT_Undefined,
886 UnaryOp=FT_Undefined,
889 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
890 aFilterMgr = self.CreateFilterManager()
891 aFilter = aFilterMgr.CreateFilter()
893 aCriteria.append(aCriterion)
894 aFilter.SetCriteria(aCriteria)
896 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
897 else : aFilter.SetMesh( mesh )
898 aFilterMgr.UnRegister()
901 ## Creates a filter from criteria
902 # @param criteria a list of criteria
903 # @param binOp binary operator used when binary operator of criteria is undefined
904 # @return SMESH_Filter
906 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
907 # @ingroup l1_controls
908 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
909 for i in range( len( criteria ) - 1 ):
910 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
911 criteria[i].BinaryOp = self.EnumToLong( binOp )
912 aFilterMgr = self.CreateFilterManager()
913 aFilter = aFilterMgr.CreateFilter()
914 aFilter.SetCriteria(criteria)
915 aFilterMgr.UnRegister()
918 ## Creates a numerical functor by its type
919 # @param theCriterion FT_...; functor type
920 # @return SMESH_NumericalFunctor
921 # @ingroup l1_controls
922 def GetFunctor(self,theCriterion):
923 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
925 aFilterMgr = self.CreateFilterManager()
927 if theCriterion == FT_AspectRatio:
928 functor = aFilterMgr.CreateAspectRatio()
929 elif theCriterion == FT_AspectRatio3D:
930 functor = aFilterMgr.CreateAspectRatio3D()
931 elif theCriterion == FT_Warping:
932 functor = aFilterMgr.CreateWarping()
933 elif theCriterion == FT_MinimumAngle:
934 functor = aFilterMgr.CreateMinimumAngle()
935 elif theCriterion == FT_Taper:
936 functor = aFilterMgr.CreateTaper()
937 elif theCriterion == FT_Skew:
938 functor = aFilterMgr.CreateSkew()
939 elif theCriterion == FT_Area:
940 functor = aFilterMgr.CreateArea()
941 elif theCriterion == FT_Volume3D:
942 functor = aFilterMgr.CreateVolume3D()
943 elif theCriterion == FT_MaxElementLength2D:
944 functor = aFilterMgr.CreateMaxElementLength2D()
945 elif theCriterion == FT_MaxElementLength3D:
946 functor = aFilterMgr.CreateMaxElementLength3D()
947 elif theCriterion == FT_MultiConnection:
948 functor = aFilterMgr.CreateMultiConnection()
949 elif theCriterion == FT_MultiConnection2D:
950 functor = aFilterMgr.CreateMultiConnection2D()
951 elif theCriterion == FT_Length:
952 functor = aFilterMgr.CreateLength()
953 elif theCriterion == FT_Length2D:
954 functor = aFilterMgr.CreateLength2D()
956 print "Error: given parameter is not numerical functor type."
957 aFilterMgr.UnRegister()
960 ## Creates hypothesis
961 # @param theHType mesh hypothesis type (string)
962 # @param theLibName mesh plug-in library name
963 # @return created hypothesis instance
964 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
965 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
967 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
970 # wrap hypothesis methods
971 #print "HYPOTHESIS", theHType
972 for meth_name in dir( hyp.__class__ ):
973 if not meth_name.startswith("Get") and \
974 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
975 method = getattr ( hyp.__class__, meth_name )
977 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
981 ## Gets the mesh statistic
982 # @return dictionary "element type" - "count of elements"
983 # @ingroup l1_meshinfo
984 def GetMeshInfo(self, obj):
985 if isinstance( obj, Mesh ):
988 if hasattr(obj, "GetMeshInfo"):
989 values = obj.GetMeshInfo()
990 for i in range(SMESH.Entity_Last._v):
991 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
995 ## Get minimum distance between two objects
997 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
998 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1000 # @param src1 first source object
1001 # @param src2 second source object
1002 # @param id1 node/element id from the first source
1003 # @param id2 node/element id from the second (or first) source
1004 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1005 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1006 # @return minimum distance value
1007 # @sa GetMinDistance()
1008 # @ingroup l1_measurements
1009 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1010 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1014 result = result.value
1017 ## Get measure structure specifying minimum distance data between two objects
1019 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1020 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1022 # @param src1 first source object
1023 # @param src2 second source object
1024 # @param id1 node/element id from the first source
1025 # @param id2 node/element id from the second (or first) source
1026 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1027 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1028 # @return Measure structure or None if input data is invalid
1030 # @ingroup l1_measurements
1031 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1032 if isinstance(src1, Mesh): src1 = src1.mesh
1033 if isinstance(src2, Mesh): src2 = src2.mesh
1034 if src2 is None and id2 != 0: src2 = src1
1035 if not hasattr(src1, "_narrow"): return None
1036 src1 = src1._narrow(SMESH.SMESH_IDSource)
1037 if not src1: return None
1038 unRegister = genObjUnRegister()
1041 e = m.GetMeshEditor()
1043 src1 = e.MakeIDSource([id1], SMESH.FACE)
1045 src1 = e.MakeIDSource([id1], SMESH.NODE)
1046 unRegister.set( src1 )
1048 if hasattr(src2, "_narrow"):
1049 src2 = src2._narrow(SMESH.SMESH_IDSource)
1050 if src2 and id2 != 0:
1052 e = m.GetMeshEditor()
1054 src2 = e.MakeIDSource([id2], SMESH.FACE)
1056 src2 = e.MakeIDSource([id2], SMESH.NODE)
1057 unRegister.set( src2 )
1060 aMeasurements = self.CreateMeasurements()
1061 unRegister.set( aMeasurements )
1062 result = aMeasurements.MinDistance(src1, src2)
1065 ## Get bounding box of the specified object(s)
1066 # @param objects single source object or list of source objects
1067 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1068 # @sa GetBoundingBox()
1069 # @ingroup l1_measurements
1070 def BoundingBox(self, objects):
1071 result = self.GetBoundingBox(objects)
1075 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1078 ## Get measure structure specifying bounding box data of the specified object(s)
1079 # @param objects single source object or list of source objects
1080 # @return Measure structure
1082 # @ingroup l1_measurements
1083 def GetBoundingBox(self, objects):
1084 if isinstance(objects, tuple):
1085 objects = list(objects)
1086 if not isinstance(objects, list):
1090 if isinstance(o, Mesh):
1091 srclist.append(o.mesh)
1092 elif hasattr(o, "_narrow"):
1093 src = o._narrow(SMESH.SMESH_IDSource)
1094 if src: srclist.append(src)
1097 aMeasurements = self.CreateMeasurements()
1098 result = aMeasurements.BoundingBox(srclist)
1099 aMeasurements.UnRegister()
1102 ## Get sum of lengths of all 1D elements in the mesh object.
1103 # @param obj mesh, submesh or group
1104 # @return sum of lengths of all 1D elements
1105 # @ingroup l1_measurements
1106 def GetLength(self, obj):
1107 if isinstance(obj, Mesh): obj = obj.mesh
1108 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1109 aMeasurements = self.CreateMeasurements()
1110 value = aMeasurements.Length(obj)
1111 aMeasurements.UnRegister()
1114 ## Get sum of areas of all 2D elements in the mesh object.
1115 # @param obj mesh, submesh or group
1116 # @return sum of areas of all 2D elements
1117 # @ingroup l1_measurements
1118 def GetArea(self, obj):
1119 if isinstance(obj, Mesh): obj = obj.mesh
1120 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1121 aMeasurements = self.CreateMeasurements()
1122 value = aMeasurements.Area(obj)
1123 aMeasurements.UnRegister()
1126 ## Get sum of volumes of all 3D elements in the mesh object.
1127 # @param obj mesh, submesh or group
1128 # @return sum of volumes of all 3D elements
1129 # @ingroup l1_measurements
1130 def GetVolume(self, obj):
1131 if isinstance(obj, Mesh): obj = obj.mesh
1132 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1133 aMeasurements = self.CreateMeasurements()
1134 value = aMeasurements.Volume(obj)
1135 aMeasurements.UnRegister()
1138 pass # end of class smeshBuilder
1141 #Registering the new proxy for SMESH_Gen
1142 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1144 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1145 # interface to create or load meshes.
1150 # salome.salome_init()
1151 # from salome.smesh import smeshBuilder
1152 # smesh = smeshBuilder.New(theStudy)
1154 # @param study SALOME study, generally obtained by salome.myStudy.
1155 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1156 # @return smeshBuilder instance
1158 def New( study, instance=None):
1160 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1161 interface to create or load meshes.
1165 salome.salome_init()
1166 from salome.smesh import smeshBuilder
1167 smesh = smeshBuilder.New(theStudy)
1170 study SALOME study, generally obtained by salome.myStudy.
1171 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1173 smeshBuilder instance
1181 smeshInst = smeshBuilder()
1182 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1183 smeshInst.init_smesh(study)
1187 # Public class: Mesh
1188 # ==================
1190 ## This class allows defining and managing a mesh.
1191 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1192 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1193 # new nodes and elements and by changing the existing entities), to get information
1194 # about a mesh and to export a mesh into different formats.
1196 __metaclass__ = MeshMeta
1204 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1205 # sets the GUI name of this mesh to \a name.
1206 # @param smeshpyD an instance of smeshBuilder class
1207 # @param geompyD an instance of geomBuilder class
1208 # @param obj Shape to be meshed or SMESH_Mesh object
1209 # @param name Study name of the mesh
1210 # @ingroup l2_construct
1211 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1212 self.smeshpyD=smeshpyD
1213 self.geompyD=geompyD
1218 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1221 # publish geom of mesh (issue 0021122)
1222 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1224 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1225 if studyID != geompyD.myStudyId:
1226 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1229 geo_name = name + " shape"
1231 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1232 geompyD.addToStudy( self.geom, geo_name )
1233 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1235 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1238 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1240 self.smeshpyD.SetName(self.mesh, name)
1242 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1245 self.geom = self.mesh.GetShapeToMesh()
1247 self.editor = self.mesh.GetMeshEditor()
1248 self.functors = [None] * SMESH.FT_Undefined._v
1250 # set self to algoCreator's
1251 for attrName in dir(self):
1252 attr = getattr( self, attrName )
1253 if isinstance( attr, algoCreator ):
1254 setattr( self, attrName, attr.copy( self ))
1259 ## Destructor. Clean-up resources
1262 #self.mesh.UnRegister()
1266 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1267 # @param theMesh a SMESH_Mesh object
1268 # @ingroup l2_construct
1269 def SetMesh(self, theMesh):
1270 # do not call Register() as this prevents mesh servant deletion at closing study
1271 #if self.mesh: self.mesh.UnRegister()
1274 #self.mesh.Register()
1275 self.geom = self.mesh.GetShapeToMesh()
1278 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1279 # @return a SMESH_Mesh object
1280 # @ingroup l2_construct
1284 ## Gets the name of the mesh
1285 # @return the name of the mesh as a string
1286 # @ingroup l2_construct
1288 name = GetName(self.GetMesh())
1291 ## Sets a name to the mesh
1292 # @param name a new name of the mesh
1293 # @ingroup l2_construct
1294 def SetName(self, name):
1295 self.smeshpyD.SetName(self.GetMesh(), name)
1297 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1298 # The subMesh object gives access to the IDs of nodes and elements.
1299 # @param geom a geometrical object (shape)
1300 # @param name a name for the submesh
1301 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1302 # @ingroup l2_submeshes
1303 def GetSubMesh(self, geom, name):
1304 AssureGeomPublished( self, geom, name )
1305 submesh = self.mesh.GetSubMesh( geom, name )
1308 ## Returns the shape associated to the mesh
1309 # @return a GEOM_Object
1310 # @ingroup l2_construct
1314 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1315 # @param geom the shape to be meshed (GEOM_Object)
1316 # @ingroup l2_construct
1317 def SetShape(self, geom):
1318 self.mesh = self.smeshpyD.CreateMesh(geom)
1320 ## Loads mesh from the study after opening the study
1324 ## Returns true if the hypotheses are defined well
1325 # @param theSubObject a sub-shape of a mesh shape
1326 # @return True or False
1327 # @ingroup l2_construct
1328 def IsReadyToCompute(self, theSubObject):
1329 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1331 ## Returns errors of hypotheses definition.
1332 # The list of errors is empty if everything is OK.
1333 # @param theSubObject a sub-shape of a mesh shape
1334 # @return a list of errors
1335 # @ingroup l2_construct
1336 def GetAlgoState(self, theSubObject):
1337 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1339 ## Returns a geometrical object on which the given element was built.
1340 # The returned geometrical object, if not nil, is either found in the
1341 # study or published by this method with the given name
1342 # @param theElementID the id of the mesh element
1343 # @param theGeomName the user-defined name of the geometrical object
1344 # @return GEOM::GEOM_Object instance
1345 # @ingroup l2_construct
1346 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1347 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1349 ## Returns the mesh dimension depending on the dimension of the underlying shape
1350 # or, if the mesh is not based on any shape, basing on deimension of elements
1351 # @return mesh dimension as an integer value [0,3]
1352 # @ingroup l1_auxiliary
1353 def MeshDimension(self):
1354 if self.mesh.HasShapeToMesh():
1355 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1356 if len( shells ) > 0 :
1358 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1360 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1365 if self.NbVolumes() > 0: return 3
1366 if self.NbFaces() > 0: return 2
1367 if self.NbEdges() > 0: return 1
1370 ## Evaluates size of prospective mesh on a shape
1371 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1372 # To know predicted number of e.g. edges, inquire it this way
1373 # Evaluate()[ EnumToLong( Entity_Edge )]
1374 def Evaluate(self, geom=0):
1375 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1377 geom = self.mesh.GetShapeToMesh()
1380 return self.smeshpyD.Evaluate(self.mesh, geom)
1383 ## Computes the mesh and returns the status of the computation
1384 # @param geom geomtrical shape on which mesh data should be computed
1385 # @param discardModifs if True and the mesh has been edited since
1386 # a last total re-compute and that may prevent successful partial re-compute,
1387 # then the mesh is cleaned before Compute()
1388 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1389 # @return True or False
1390 # @ingroup l2_construct
1391 def Compute(self, geom=0, discardModifs=False, refresh=False):
1392 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1394 geom = self.mesh.GetShapeToMesh()
1399 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1401 ok = self.smeshpyD.Compute(self.mesh, geom)
1402 except SALOME.SALOME_Exception, ex:
1403 print "Mesh computation failed, exception caught:"
1404 print " ", ex.details.text
1407 print "Mesh computation failed, exception caught:"
1408 traceback.print_exc()
1412 # Treat compute errors
1413 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1414 for err in computeErrors:
1416 if self.mesh.HasShapeToMesh():
1418 mainIOR = salome.orb.object_to_string(geom)
1419 for sname in salome.myStudyManager.GetOpenStudies():
1420 s = salome.myStudyManager.GetStudyByName(sname)
1422 mainSO = s.FindObjectIOR(mainIOR)
1423 if not mainSO: continue
1424 if err.subShapeID == 1:
1425 shapeText = ' on "%s"' % mainSO.GetName()
1426 subIt = s.NewChildIterator(mainSO)
1428 subSO = subIt.Value()
1430 obj = subSO.GetObject()
1431 if not obj: continue
1432 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1434 ids = go.GetSubShapeIndices()
1435 if len(ids) == 1 and ids[0] == err.subShapeID:
1436 shapeText = ' on "%s"' % subSO.GetName()
1439 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1441 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1443 shapeText = " on subshape #%s" % (err.subShapeID)
1445 shapeText = " on subshape #%s" % (err.subShapeID)
1447 stdErrors = ["OK", #COMPERR_OK
1448 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1449 "std::exception", #COMPERR_STD_EXCEPTION
1450 "OCC exception", #COMPERR_OCC_EXCEPTION
1451 "..", #COMPERR_SLM_EXCEPTION
1452 "Unknown exception", #COMPERR_EXCEPTION
1453 "Memory allocation problem", #COMPERR_MEMORY_PB
1454 "Algorithm failed", #COMPERR_ALGO_FAILED
1455 "Unexpected geometry", #COMPERR_BAD_SHAPE
1456 "Warning", #COMPERR_WARNING
1457 "Computation cancelled",#COMPERR_CANCELED
1458 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1460 if err.code < len(stdErrors): errText = stdErrors[err.code]
1462 errText = "code %s" % -err.code
1463 if errText: errText += ". "
1464 errText += err.comment
1465 if allReasons != "":allReasons += "\n"
1467 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1469 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1473 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1475 if err.isGlobalAlgo:
1483 reason = '%s %sD algorithm is missing' % (glob, dim)
1484 elif err.state == HYP_MISSING:
1485 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1486 % (glob, dim, name, dim))
1487 elif err.state == HYP_NOTCONFORM:
1488 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1489 elif err.state == HYP_BAD_PARAMETER:
1490 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1491 % ( glob, dim, name ))
1492 elif err.state == HYP_BAD_GEOMETRY:
1493 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1494 'geometry' % ( glob, dim, name ))
1495 elif err.state == HYP_HIDDEN_ALGO:
1496 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1497 'algorithm of upper dimension generating %sD mesh'
1498 % ( glob, dim, name, glob, dim ))
1500 reason = ("For unknown reason. "
1501 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1503 if allReasons != "":allReasons += "\n"
1504 allReasons += "- " + reason
1506 if not ok or allReasons != "":
1507 msg = '"' + GetName(self.mesh) + '"'
1508 if ok: msg += " has been computed with warnings"
1509 else: msg += " has not been computed"
1510 if allReasons != "": msg += ":"
1515 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1516 smeshgui = salome.ImportComponentGUI("SMESH")
1517 smeshgui.Init(self.mesh.GetStudyId())
1518 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1519 if refresh: salome.sg.updateObjBrowser(1)
1523 ## Return submesh objects list in meshing order
1524 # @return list of list of submesh objects
1525 # @ingroup l2_construct
1526 def GetMeshOrder(self):
1527 return self.mesh.GetMeshOrder()
1529 ## Return submesh objects list in meshing order
1530 # @return list of list of submesh objects
1531 # @ingroup l2_construct
1532 def SetMeshOrder(self, submeshes):
1533 return self.mesh.SetMeshOrder(submeshes)
1535 ## Removes all nodes and elements
1536 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1537 # @ingroup l2_construct
1538 def Clear(self, refresh=False):
1540 if ( salome.sg.hasDesktop() and
1541 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1542 smeshgui = salome.ImportComponentGUI("SMESH")
1543 smeshgui.Init(self.mesh.GetStudyId())
1544 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1545 if refresh: salome.sg.updateObjBrowser(1)
1547 ## Removes all nodes and elements of indicated shape
1548 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1549 # @param geomId the ID of a sub-shape to remove elements on
1550 # @ingroup l2_construct
1551 def ClearSubMesh(self, geomId, refresh=False):
1552 self.mesh.ClearSubMesh(geomId)
1553 if salome.sg.hasDesktop():
1554 smeshgui = salome.ImportComponentGUI("SMESH")
1555 smeshgui.Init(self.mesh.GetStudyId())
1556 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1557 if refresh: salome.sg.updateObjBrowser(1)
1559 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1560 # @param fineness [0.0,1.0] defines mesh fineness
1561 # @return True or False
1562 # @ingroup l3_algos_basic
1563 def AutomaticTetrahedralization(self, fineness=0):
1564 dim = self.MeshDimension()
1566 self.RemoveGlobalHypotheses()
1567 self.Segment().AutomaticLength(fineness)
1569 self.Triangle().LengthFromEdges()
1574 return self.Compute()
1576 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1577 # @param fineness [0.0, 1.0] defines mesh fineness
1578 # @return True or False
1579 # @ingroup l3_algos_basic
1580 def AutomaticHexahedralization(self, fineness=0):
1581 dim = self.MeshDimension()
1582 # assign the hypotheses
1583 self.RemoveGlobalHypotheses()
1584 self.Segment().AutomaticLength(fineness)
1591 return self.Compute()
1593 ## Assigns a hypothesis
1594 # @param hyp a hypothesis to assign
1595 # @param geom a subhape of mesh geometry
1596 # @return SMESH.Hypothesis_Status
1597 # @ingroup l2_hypotheses
1598 def AddHypothesis(self, hyp, geom=0):
1599 if isinstance( hyp, Mesh_Algorithm ):
1600 hyp = hyp.GetAlgorithm()
1605 geom = self.mesh.GetShapeToMesh()
1608 if self.mesh.HasShapeToMesh():
1609 hyp_type = hyp.GetName()
1610 lib_name = hyp.GetLibName()
1611 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1612 if checkAll and geom:
1613 checkAll = geom.GetType() == 37
1614 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1616 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1617 status = self.mesh.AddHypothesis(geom, hyp)
1619 status = HYP_BAD_GEOMETRY,""
1620 hyp_name = GetName( hyp )
1623 geom_name = geom.GetName()
1624 isAlgo = hyp._narrow( SMESH_Algo )
1625 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1628 ## Return True if an algorithm of hypothesis is assigned to a given shape
1629 # @param hyp a hypothesis to check
1630 # @param geom a subhape of mesh geometry
1631 # @return True of False
1632 # @ingroup l2_hypotheses
1633 def IsUsedHypothesis(self, hyp, geom):
1634 if not hyp: # or not geom
1636 if isinstance( hyp, Mesh_Algorithm ):
1637 hyp = hyp.GetAlgorithm()
1639 hyps = self.GetHypothesisList(geom)
1641 if h.GetId() == hyp.GetId():
1645 ## Unassigns a hypothesis
1646 # @param hyp a hypothesis to unassign
1647 # @param geom a sub-shape of mesh geometry
1648 # @return SMESH.Hypothesis_Status
1649 # @ingroup l2_hypotheses
1650 def RemoveHypothesis(self, hyp, geom=0):
1653 if isinstance( hyp, Mesh_Algorithm ):
1654 hyp = hyp.GetAlgorithm()
1660 if self.IsUsedHypothesis( hyp, shape ):
1661 return self.mesh.RemoveHypothesis( shape, hyp )
1662 hypName = GetName( hyp )
1663 geoName = GetName( shape )
1664 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1667 ## Gets the list of hypotheses added on a geometry
1668 # @param geom a sub-shape of mesh geometry
1669 # @return the sequence of SMESH_Hypothesis
1670 # @ingroup l2_hypotheses
1671 def GetHypothesisList(self, geom):
1672 return self.mesh.GetHypothesisList( geom )
1674 ## Removes all global hypotheses
1675 # @ingroup l2_hypotheses
1676 def RemoveGlobalHypotheses(self):
1677 current_hyps = self.mesh.GetHypothesisList( self.geom )
1678 for hyp in current_hyps:
1679 self.mesh.RemoveHypothesis( self.geom, hyp )
1683 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1684 ## allowing to overwrite the file if it exists or add the exported data to its contents
1685 # @param f is the file name
1686 # @param auto_groups boolean parameter for creating/not creating
1687 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1688 # the typical use is auto_groups=false.
1689 # @param version MED format version(MED_V2_1 or MED_V2_2)
1690 # @param overwrite boolean parameter for overwriting/not overwriting the file
1691 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1692 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1693 # - 1D if all mesh nodes lie on OX coordinate axis, or
1694 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1695 # - 3D in the rest cases.
1696 # If @a autoDimension is @c False, the space dimension is always 3.
1697 # @param fields : list of GEOM fields defined on the shape to mesh.
1698 # @param geomAssocFields : each character of this string means a need to export a
1699 # corresponding field; correspondence between fields and characters is following:
1700 # - 'v' stands for _vertices_ field;
1701 # - 'e' stands for _edges_ field;
1702 # - 'f' stands for _faces_ field;
1703 # - 's' stands for _solids_ field.
1704 # @ingroup l2_impexp
1705 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1706 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1707 if meshPart or fields or geomAssocFields:
1708 unRegister = genObjUnRegister()
1709 if isinstance( meshPart, list ):
1710 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1711 unRegister.set( meshPart )
1712 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1713 fields, geomAssocFields)
1715 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1717 ## Exports the mesh in a file in SAUV format
1718 # @param f is the file name
1719 # @param auto_groups boolean parameter for creating/not creating
1720 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1721 # the typical use is auto_groups=false.
1722 # @ingroup l2_impexp
1723 def ExportSAUV(self, f, auto_groups=0):
1724 self.mesh.ExportSAUV(f, auto_groups)
1726 ## Exports the mesh in a file in DAT format
1727 # @param f the file name
1728 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1729 # @ingroup l2_impexp
1730 def ExportDAT(self, f, meshPart=None):
1732 unRegister = genObjUnRegister()
1733 if isinstance( meshPart, list ):
1734 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1735 unRegister.set( meshPart )
1736 self.mesh.ExportPartToDAT( meshPart, f )
1738 self.mesh.ExportDAT(f)
1740 ## Exports the mesh in a file in UNV format
1741 # @param f the file name
1742 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1743 # @ingroup l2_impexp
1744 def ExportUNV(self, f, meshPart=None):
1746 unRegister = genObjUnRegister()
1747 if isinstance( meshPart, list ):
1748 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1749 unRegister.set( meshPart )
1750 self.mesh.ExportPartToUNV( meshPart, f )
1752 self.mesh.ExportUNV(f)
1754 ## Export the mesh in a file in STL format
1755 # @param f the file name
1756 # @param ascii defines the file encoding
1757 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1758 # @ingroup l2_impexp
1759 def ExportSTL(self, f, ascii=1, meshPart=None):
1761 unRegister = genObjUnRegister()
1762 if isinstance( meshPart, list ):
1763 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1764 unRegister.set( meshPart )
1765 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1767 self.mesh.ExportSTL(f, ascii)
1769 ## Exports the mesh in a file in CGNS format
1770 # @param f is the file name
1771 # @param overwrite boolean parameter for overwriting/not overwriting the file
1772 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1773 # @ingroup l2_impexp
1774 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1775 unRegister = genObjUnRegister()
1776 if isinstance( meshPart, list ):
1777 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1778 unRegister.set( meshPart )
1779 if isinstance( meshPart, Mesh ):
1780 meshPart = meshPart.mesh
1782 meshPart = self.mesh
1783 self.mesh.ExportCGNS(meshPart, f, overwrite)
1785 ## Exports the mesh in a file in GMF format.
1786 # GMF files must have .mesh extension for the ASCII format and .meshb for
1787 # the bynary format. Other extensions are not allowed.
1788 # @param f is the file name
1789 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1790 # @ingroup l2_impexp
1791 def ExportGMF(self, f, meshPart=None):
1792 unRegister = genObjUnRegister()
1793 if isinstance( meshPart, list ):
1794 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1795 unRegister.set( meshPart )
1796 if isinstance( meshPart, Mesh ):
1797 meshPart = meshPart.mesh
1799 meshPart = self.mesh
1800 self.mesh.ExportGMF(meshPart, f, True)
1802 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1803 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1804 ## allowing to overwrite the file if it exists or add the exported data to its contents
1805 # @param f the file name
1806 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1807 # @param opt boolean parameter for creating/not creating
1808 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1809 # @param overwrite boolean parameter for overwriting/not overwriting the file
1810 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1811 # - 1D if all mesh nodes lie on OX coordinate axis, or
1812 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1813 # - 3D in the rest cases.
1815 # If @a autoDimension is @c False, the space dimension is always 3.
1816 # @ingroup l2_impexp
1817 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1818 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1820 # Operations with groups:
1821 # ----------------------
1823 ## Creates an empty mesh group
1824 # @param elementType the type of elements in the group
1825 # @param name the name of the mesh group
1826 # @return SMESH_Group
1827 # @ingroup l2_grps_create
1828 def CreateEmptyGroup(self, elementType, name):
1829 return self.mesh.CreateGroup(elementType, name)
1831 ## Creates a mesh group based on the geometric object \a grp
1832 # and gives a \a name, \n if this parameter is not defined
1833 # the name is the same as the geometric group name \n
1834 # Note: Works like GroupOnGeom().
1835 # @param grp a geometric group, a vertex, an edge, a face or a solid
1836 # @param name the name of the mesh group
1837 # @return SMESH_GroupOnGeom
1838 # @ingroup l2_grps_create
1839 def Group(self, grp, name=""):
1840 return self.GroupOnGeom(grp, name)
1842 ## Creates a mesh group based on the geometrical object \a grp
1843 # and gives a \a name, \n if this parameter is not defined
1844 # the name is the same as the geometrical group name
1845 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1846 # @param name the name of the mesh group
1847 # @param typ the type of elements in the group. If not set, it is
1848 # automatically detected by the type of the geometry
1849 # @return SMESH_GroupOnGeom
1850 # @ingroup l2_grps_create
1851 def GroupOnGeom(self, grp, name="", typ=None):
1852 AssureGeomPublished( self, grp, name )
1854 name = grp.GetName()
1856 typ = self._groupTypeFromShape( grp )
1857 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1859 ## Pivate method to get a type of group on geometry
1860 def _groupTypeFromShape( self, shape ):
1861 tgeo = str(shape.GetShapeType())
1862 if tgeo == "VERTEX":
1864 elif tgeo == "EDGE":
1866 elif tgeo == "FACE" or tgeo == "SHELL":
1868 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1870 elif tgeo == "COMPOUND":
1871 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1873 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1874 return self._groupTypeFromShape( sub[0] )
1877 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1880 ## Creates a mesh group with given \a name based on the \a filter which
1881 ## is a special type of group dynamically updating it's contents during
1882 ## mesh modification
1883 # @param typ the type of elements in the group
1884 # @param name the name of the mesh group
1885 # @param filter the filter defining group contents
1886 # @return SMESH_GroupOnFilter
1887 # @ingroup l2_grps_create
1888 def GroupOnFilter(self, typ, name, filter):
1889 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1891 ## Creates a mesh group by the given ids of elements
1892 # @param groupName the name of the mesh group
1893 # @param elementType the type of elements in the group
1894 # @param elemIDs the list of ids
1895 # @return SMESH_Group
1896 # @ingroup l2_grps_create
1897 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1898 group = self.mesh.CreateGroup(elementType, groupName)
1899 if hasattr( elemIDs, "GetIDs" ):
1900 if hasattr( elemIDs, "SetMesh" ):
1901 elemIDs.SetMesh( self.GetMesh() )
1902 group.AddFrom( elemIDs )
1907 ## Creates a mesh group by the given conditions
1908 # @param groupName the name of the mesh group
1909 # @param elementType the type of elements in the group
1910 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1911 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1912 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1913 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1914 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1915 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1916 # @return SMESH_GroupOnFilter
1917 # @ingroup l2_grps_create
1921 CritType=FT_Undefined,
1924 UnaryOp=FT_Undefined,
1926 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1927 group = self.MakeGroupByCriterion(groupName, aCriterion)
1930 ## Creates a mesh group by the given criterion
1931 # @param groupName the name of the mesh group
1932 # @param Criterion the instance of Criterion class
1933 # @return SMESH_GroupOnFilter
1934 # @ingroup l2_grps_create
1935 def MakeGroupByCriterion(self, groupName, Criterion):
1936 return self.MakeGroupByCriteria( groupName, [Criterion] )
1938 ## Creates a mesh group by the given criteria (list of criteria)
1939 # @param groupName the name of the mesh group
1940 # @param theCriteria the list of criteria
1941 # @param binOp binary operator used when binary operator of criteria is undefined
1942 # @return SMESH_GroupOnFilter
1943 # @ingroup l2_grps_create
1944 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1945 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1946 group = self.MakeGroupByFilter(groupName, aFilter)
1949 ## Creates a mesh group by the given filter
1950 # @param groupName the name of the mesh group
1951 # @param theFilter the instance of Filter class
1952 # @return SMESH_GroupOnFilter
1953 # @ingroup l2_grps_create
1954 def MakeGroupByFilter(self, groupName, theFilter):
1955 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1956 #theFilter.SetMesh( self.mesh )
1957 #group.AddFrom( theFilter )
1958 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1962 # @ingroup l2_grps_delete
1963 def RemoveGroup(self, group):
1964 self.mesh.RemoveGroup(group)
1966 ## Removes a group with its contents
1967 # @ingroup l2_grps_delete
1968 def RemoveGroupWithContents(self, group):
1969 self.mesh.RemoveGroupWithContents(group)
1971 ## Gets the list of groups existing in the mesh in the order
1972 # of creation (starting from the oldest one)
1973 # @return a sequence of SMESH_GroupBase
1974 # @ingroup l2_grps_create
1975 def GetGroups(self):
1976 return self.mesh.GetGroups()
1978 ## Gets the number of groups existing in the mesh
1979 # @return the quantity of groups as an integer value
1980 # @ingroup l2_grps_create
1982 return self.mesh.NbGroups()
1984 ## Gets the list of names of groups existing in the mesh
1985 # @return list of strings
1986 # @ingroup l2_grps_create
1987 def GetGroupNames(self):
1988 groups = self.GetGroups()
1990 for group in groups:
1991 names.append(group.GetName())
1994 ## Produces a union of two groups.
1995 # A new group is created. All mesh elements that are
1996 # present in the initial groups are added to the new one
1997 # @return an instance of SMESH_Group
1998 # @ingroup l2_grps_operon
1999 def UnionGroups(self, group1, group2, name):
2000 return self.mesh.UnionGroups(group1, group2, name)
2002 ## Produces a union list of groups.
2003 # New group is created. All mesh elements that are present in
2004 # initial groups are added to the new one
2005 # @return an instance of SMESH_Group
2006 # @ingroup l2_grps_operon
2007 def UnionListOfGroups(self, groups, name):
2008 return self.mesh.UnionListOfGroups(groups, name)
2010 ## Prodices an intersection of two groups.
2011 # A new group is created. All mesh elements that are common
2012 # for the two initial groups are added to the new one.
2013 # @return an instance of SMESH_Group
2014 # @ingroup l2_grps_operon
2015 def IntersectGroups(self, group1, group2, name):
2016 return self.mesh.IntersectGroups(group1, group2, name)
2018 ## Produces an intersection of groups.
2019 # New group is created. All mesh elements that are present in all
2020 # initial groups simultaneously are added to the new one
2021 # @return an instance of SMESH_Group
2022 # @ingroup l2_grps_operon
2023 def IntersectListOfGroups(self, groups, name):
2024 return self.mesh.IntersectListOfGroups(groups, name)
2026 ## Produces a cut of two groups.
2027 # A new group is created. All mesh elements that are present in
2028 # the main group but are not present in the tool group are added to the new one
2029 # @return an instance of SMESH_Group
2030 # @ingroup l2_grps_operon
2031 def CutGroups(self, main_group, tool_group, name):
2032 return self.mesh.CutGroups(main_group, tool_group, name)
2034 ## Produces a cut of groups.
2035 # A new group is created. All mesh elements that are present in main groups
2036 # but do not present in tool groups are added to the new one
2037 # @return an instance of SMESH_Group
2038 # @ingroup l2_grps_operon
2039 def CutListOfGroups(self, main_groups, tool_groups, name):
2040 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2043 # Create a standalone group of entities basing on nodes of other groups.
2044 # \param groups - list of groups, sub-meshes or filters, of any type.
2045 # \param elemType - a type of elements to include to the new group.
2046 # \param name - a name of the new group.
2047 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2048 # basing on number of element nodes common with reference \a groups.
2049 # Meaning of possible values are:
2050 # - SMESH.ALL_NODES - include if all nodes are common,
2051 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2052 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2053 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2054 # \param underlyingOnly - if \c True (default), an element is included to the
2055 # new group provided that it is based on nodes of one element of \a groups.
2056 # @return an instance of SMESH_Group
2057 # @ingroup l2_grps_operon
2058 def CreateDimGroup(self, groups, elemType, name,
2059 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2060 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2062 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2065 ## Convert group on geom into standalone group
2066 # @ingroup l2_grps_delete
2067 def ConvertToStandalone(self, group):
2068 return self.mesh.ConvertToStandalone(group)
2070 # Get some info about mesh:
2071 # ------------------------
2073 ## Returns the log of nodes and elements added or removed
2074 # since the previous clear of the log.
2075 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2076 # @return list of log_block structures:
2081 # @ingroup l1_auxiliary
2082 def GetLog(self, clearAfterGet):
2083 return self.mesh.GetLog(clearAfterGet)
2085 ## Clears the log of nodes and elements added or removed since the previous
2086 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2087 # @ingroup l1_auxiliary
2089 self.mesh.ClearLog()
2091 ## Toggles auto color mode on the object.
2092 # @param theAutoColor the flag which toggles auto color mode.
2093 # @ingroup l1_auxiliary
2094 def SetAutoColor(self, theAutoColor):
2095 self.mesh.SetAutoColor(theAutoColor)
2097 ## Gets flag of object auto color mode.
2098 # @return True or False
2099 # @ingroup l1_auxiliary
2100 def GetAutoColor(self):
2101 return self.mesh.GetAutoColor()
2103 ## Gets the internal ID
2104 # @return integer value, which is the internal Id of the mesh
2105 # @ingroup l1_auxiliary
2107 return self.mesh.GetId()
2110 # @return integer value, which is the study Id of the mesh
2111 # @ingroup l1_auxiliary
2112 def GetStudyId(self):
2113 return self.mesh.GetStudyId()
2115 ## Checks the group names for duplications.
2116 # Consider the maximum group name length stored in MED file.
2117 # @return True or False
2118 # @ingroup l1_auxiliary
2119 def HasDuplicatedGroupNamesMED(self):
2120 return self.mesh.HasDuplicatedGroupNamesMED()
2122 ## Obtains the mesh editor tool
2123 # @return an instance of SMESH_MeshEditor
2124 # @ingroup l1_modifying
2125 def GetMeshEditor(self):
2128 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2129 # can be passed as argument to a method accepting mesh, group or sub-mesh
2130 # @return an instance of SMESH_IDSource
2131 # @ingroup l1_auxiliary
2132 def GetIDSource(self, ids, elemType):
2133 return self.editor.MakeIDSource(ids, elemType)
2136 # Get informations about mesh contents:
2137 # ------------------------------------
2139 ## Gets the mesh stattistic
2140 # @return dictionary type element - count of elements
2141 # @ingroup l1_meshinfo
2142 def GetMeshInfo(self, obj = None):
2143 if not obj: obj = self.mesh
2144 return self.smeshpyD.GetMeshInfo(obj)
2146 ## Returns the number of nodes in the mesh
2147 # @return an integer value
2148 # @ingroup l1_meshinfo
2150 return self.mesh.NbNodes()
2152 ## Returns the number of elements in the mesh
2153 # @return an integer value
2154 # @ingroup l1_meshinfo
2155 def NbElements(self):
2156 return self.mesh.NbElements()
2158 ## Returns the number of 0d elements in the mesh
2159 # @return an integer value
2160 # @ingroup l1_meshinfo
2161 def Nb0DElements(self):
2162 return self.mesh.Nb0DElements()
2164 ## Returns the number of ball discrete elements in the mesh
2165 # @return an integer value
2166 # @ingroup l1_meshinfo
2168 return self.mesh.NbBalls()
2170 ## Returns the number of edges in the mesh
2171 # @return an integer value
2172 # @ingroup l1_meshinfo
2174 return self.mesh.NbEdges()
2176 ## Returns the number of edges with the given order in the mesh
2177 # @param elementOrder the order of elements:
2178 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2179 # @return an integer value
2180 # @ingroup l1_meshinfo
2181 def NbEdgesOfOrder(self, elementOrder):
2182 return self.mesh.NbEdgesOfOrder(elementOrder)
2184 ## Returns the number of faces in the mesh
2185 # @return an integer value
2186 # @ingroup l1_meshinfo
2188 return self.mesh.NbFaces()
2190 ## Returns the number of faces with the given order in the mesh
2191 # @param elementOrder the order of elements:
2192 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2193 # @return an integer value
2194 # @ingroup l1_meshinfo
2195 def NbFacesOfOrder(self, elementOrder):
2196 return self.mesh.NbFacesOfOrder(elementOrder)
2198 ## Returns the number of triangles in the mesh
2199 # @return an integer value
2200 # @ingroup l1_meshinfo
2201 def NbTriangles(self):
2202 return self.mesh.NbTriangles()
2204 ## Returns the number of triangles with the given order in the mesh
2205 # @param elementOrder is the order of elements:
2206 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2207 # @return an integer value
2208 # @ingroup l1_meshinfo
2209 def NbTrianglesOfOrder(self, elementOrder):
2210 return self.mesh.NbTrianglesOfOrder(elementOrder)
2212 ## Returns the number of biquadratic triangles in the mesh
2213 # @return an integer value
2214 # @ingroup l1_meshinfo
2215 def NbBiQuadTriangles(self):
2216 return self.mesh.NbBiQuadTriangles()
2218 ## Returns the number of quadrangles in the mesh
2219 # @return an integer value
2220 # @ingroup l1_meshinfo
2221 def NbQuadrangles(self):
2222 return self.mesh.NbQuadrangles()
2224 ## Returns the number of quadrangles with the given order in the mesh
2225 # @param elementOrder the order of elements:
2226 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2227 # @return an integer value
2228 # @ingroup l1_meshinfo
2229 def NbQuadranglesOfOrder(self, elementOrder):
2230 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2232 ## Returns the number of biquadratic quadrangles in the mesh
2233 # @return an integer value
2234 # @ingroup l1_meshinfo
2235 def NbBiQuadQuadrangles(self):
2236 return self.mesh.NbBiQuadQuadrangles()
2238 ## Returns the number of polygons in the mesh
2239 # @return an integer value
2240 # @ingroup l1_meshinfo
2241 def NbPolygons(self):
2242 return self.mesh.NbPolygons()
2244 ## Returns the number of volumes in the mesh
2245 # @return an integer value
2246 # @ingroup l1_meshinfo
2247 def NbVolumes(self):
2248 return self.mesh.NbVolumes()
2250 ## Returns the number of volumes with the given order in the mesh
2251 # @param elementOrder the order of elements:
2252 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2253 # @return an integer value
2254 # @ingroup l1_meshinfo
2255 def NbVolumesOfOrder(self, elementOrder):
2256 return self.mesh.NbVolumesOfOrder(elementOrder)
2258 ## Returns the number of tetrahedrons in the mesh
2259 # @return an integer value
2260 # @ingroup l1_meshinfo
2262 return self.mesh.NbTetras()
2264 ## Returns the number of tetrahedrons with the given order in the mesh
2265 # @param elementOrder the order of elements:
2266 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2267 # @return an integer value
2268 # @ingroup l1_meshinfo
2269 def NbTetrasOfOrder(self, elementOrder):
2270 return self.mesh.NbTetrasOfOrder(elementOrder)
2272 ## Returns the number of hexahedrons in the mesh
2273 # @return an integer value
2274 # @ingroup l1_meshinfo
2276 return self.mesh.NbHexas()
2278 ## Returns the number of hexahedrons with the given order in the mesh
2279 # @param elementOrder the order of elements:
2280 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2281 # @return an integer value
2282 # @ingroup l1_meshinfo
2283 def NbHexasOfOrder(self, elementOrder):
2284 return self.mesh.NbHexasOfOrder(elementOrder)
2286 ## Returns the number of triquadratic hexahedrons in the mesh
2287 # @return an integer value
2288 # @ingroup l1_meshinfo
2289 def NbTriQuadraticHexas(self):
2290 return self.mesh.NbTriQuadraticHexas()
2292 ## Returns the number of pyramids in the mesh
2293 # @return an integer value
2294 # @ingroup l1_meshinfo
2295 def NbPyramids(self):
2296 return self.mesh.NbPyramids()
2298 ## Returns the number of pyramids with the given order in the mesh
2299 # @param elementOrder the order of elements:
2300 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2301 # @return an integer value
2302 # @ingroup l1_meshinfo
2303 def NbPyramidsOfOrder(self, elementOrder):
2304 return self.mesh.NbPyramidsOfOrder(elementOrder)
2306 ## Returns the number of prisms in the mesh
2307 # @return an integer value
2308 # @ingroup l1_meshinfo
2310 return self.mesh.NbPrisms()
2312 ## Returns the number of prisms with the given order in the mesh
2313 # @param elementOrder the order of elements:
2314 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2315 # @return an integer value
2316 # @ingroup l1_meshinfo
2317 def NbPrismsOfOrder(self, elementOrder):
2318 return self.mesh.NbPrismsOfOrder(elementOrder)
2320 ## Returns the number of hexagonal prisms in the mesh
2321 # @return an integer value
2322 # @ingroup l1_meshinfo
2323 def NbHexagonalPrisms(self):
2324 return self.mesh.NbHexagonalPrisms()
2326 ## Returns the number of polyhedrons in the mesh
2327 # @return an integer value
2328 # @ingroup l1_meshinfo
2329 def NbPolyhedrons(self):
2330 return self.mesh.NbPolyhedrons()
2332 ## Returns the number of submeshes in the mesh
2333 # @return an integer value
2334 # @ingroup l1_meshinfo
2335 def NbSubMesh(self):
2336 return self.mesh.NbSubMesh()
2338 ## Returns the list of mesh elements IDs
2339 # @return the list of integer values
2340 # @ingroup l1_meshinfo
2341 def GetElementsId(self):
2342 return self.mesh.GetElementsId()
2344 ## Returns the list of IDs of mesh elements with the given type
2345 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2346 # @return list of integer values
2347 # @ingroup l1_meshinfo
2348 def GetElementsByType(self, elementType):
2349 return self.mesh.GetElementsByType(elementType)
2351 ## Returns the list of mesh nodes IDs
2352 # @return the list of integer values
2353 # @ingroup l1_meshinfo
2354 def GetNodesId(self):
2355 return self.mesh.GetNodesId()
2357 # Get the information about mesh elements:
2358 # ------------------------------------
2360 ## Returns the type of mesh element
2361 # @return the value from SMESH::ElementType enumeration
2362 # @ingroup l1_meshinfo
2363 def GetElementType(self, id, iselem):
2364 return self.mesh.GetElementType(id, iselem)
2366 ## Returns the geometric type of mesh element
2367 # @return the value from SMESH::EntityType enumeration
2368 # @ingroup l1_meshinfo
2369 def GetElementGeomType(self, id):
2370 return self.mesh.GetElementGeomType(id)
2372 ## Returns the shape type of mesh element
2373 # @return the value from SMESH::GeometryType enumeration
2374 # @ingroup l1_meshinfo
2375 def GetElementShape(self, id):
2376 return self.mesh.GetElementShape(id)
2378 ## Returns the list of submesh elements IDs
2379 # @param Shape a geom object(sub-shape) IOR
2380 # Shape must be the sub-shape of a ShapeToMesh()
2381 # @return the list of integer values
2382 # @ingroup l1_meshinfo
2383 def GetSubMeshElementsId(self, Shape):
2384 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2385 ShapeID = Shape.GetSubShapeIndices()[0]
2388 return self.mesh.GetSubMeshElementsId(ShapeID)
2390 ## Returns the list of submesh nodes IDs
2391 # @param Shape a geom object(sub-shape) IOR
2392 # Shape must be the sub-shape of a ShapeToMesh()
2393 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2394 # @return the list of integer values
2395 # @ingroup l1_meshinfo
2396 def GetSubMeshNodesId(self, Shape, all):
2397 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2398 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2401 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2403 ## Returns type of elements on given shape
2404 # @param Shape a geom object(sub-shape) IOR
2405 # Shape must be a sub-shape of a ShapeToMesh()
2406 # @return element type
2407 # @ingroup l1_meshinfo
2408 def GetSubMeshElementType(self, Shape):
2409 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2410 ShapeID = Shape.GetSubShapeIndices()[0]
2413 return self.mesh.GetSubMeshElementType(ShapeID)
2415 ## Gets the mesh description
2416 # @return string value
2417 # @ingroup l1_meshinfo
2419 return self.mesh.Dump()
2422 # Get the information about nodes and elements of a mesh by its IDs:
2423 # -----------------------------------------------------------
2425 ## Gets XYZ coordinates of a node
2426 # \n If there is no nodes for the given ID - returns an empty list
2427 # @return a list of double precision values
2428 # @ingroup l1_meshinfo
2429 def GetNodeXYZ(self, id):
2430 return self.mesh.GetNodeXYZ(id)
2432 ## Returns list of IDs of inverse elements for the given node
2433 # \n If there is no node for the given ID - returns an empty list
2434 # @return a list of integer values
2435 # @ingroup l1_meshinfo
2436 def GetNodeInverseElements(self, id):
2437 return self.mesh.GetNodeInverseElements(id)
2439 ## @brief Returns the position of a node on the shape
2440 # @return SMESH::NodePosition
2441 # @ingroup l1_meshinfo
2442 def GetNodePosition(self,NodeID):
2443 return self.mesh.GetNodePosition(NodeID)
2445 ## @brief Returns the position of an element on the shape
2446 # @return SMESH::ElementPosition
2447 # @ingroup l1_meshinfo
2448 def GetElementPosition(self,ElemID):
2449 return self.mesh.GetElementPosition(ElemID)
2451 ## If the given element is a node, returns the ID of shape
2452 # \n If there is no node for the given ID - returns -1
2453 # @return an integer value
2454 # @ingroup l1_meshinfo
2455 def GetShapeID(self, id):
2456 return self.mesh.GetShapeID(id)
2458 ## Returns the ID of the result shape after
2459 # FindShape() from SMESH_MeshEditor for the given element
2460 # \n If there is no element for the given ID - returns -1
2461 # @return an integer value
2462 # @ingroup l1_meshinfo
2463 def GetShapeIDForElem(self,id):
2464 return self.mesh.GetShapeIDForElem(id)
2466 ## Returns the number of nodes for the given element
2467 # \n If there is no element for the given ID - returns -1
2468 # @return an integer value
2469 # @ingroup l1_meshinfo
2470 def GetElemNbNodes(self, id):
2471 return self.mesh.GetElemNbNodes(id)
2473 ## Returns the node ID the given (zero based) index for the given element
2474 # \n If there is no element for the given ID - returns -1
2475 # \n If there is no node for the given index - returns -2
2476 # @return an integer value
2477 # @ingroup l1_meshinfo
2478 def GetElemNode(self, id, index):
2479 return self.mesh.GetElemNode(id, index)
2481 ## Returns the IDs of nodes of the given element
2482 # @return a list of integer values
2483 # @ingroup l1_meshinfo
2484 def GetElemNodes(self, id):
2485 return self.mesh.GetElemNodes(id)
2487 ## Returns true if the given node is the medium node in the given quadratic element
2488 # @ingroup l1_meshinfo
2489 def IsMediumNode(self, elementID, nodeID):
2490 return self.mesh.IsMediumNode(elementID, nodeID)
2492 ## Returns true if the given node is the medium node in one of quadratic elements
2493 # @ingroup l1_meshinfo
2494 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2495 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2497 ## Returns the number of edges for the given element
2498 # @ingroup l1_meshinfo
2499 def ElemNbEdges(self, id):
2500 return self.mesh.ElemNbEdges(id)
2502 ## Returns the number of faces for the given element
2503 # @ingroup l1_meshinfo
2504 def ElemNbFaces(self, id):
2505 return self.mesh.ElemNbFaces(id)
2507 ## Returns nodes of given face (counted from zero) for given volumic element.
2508 # @ingroup l1_meshinfo
2509 def GetElemFaceNodes(self,elemId, faceIndex):
2510 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2512 ## Returns three components of normal of given mesh face
2513 # (or an empty array in KO case)
2514 # @ingroup l1_meshinfo
2515 def GetFaceNormal(self, faceId, normalized=False):
2516 return self.mesh.GetFaceNormal(faceId,normalized)
2518 ## Returns an element based on all given nodes.
2519 # @ingroup l1_meshinfo
2520 def FindElementByNodes(self,nodes):
2521 return self.mesh.FindElementByNodes(nodes)
2523 ## Returns true if the given element is a polygon
2524 # @ingroup l1_meshinfo
2525 def IsPoly(self, id):
2526 return self.mesh.IsPoly(id)
2528 ## Returns true if the given element is quadratic
2529 # @ingroup l1_meshinfo
2530 def IsQuadratic(self, id):
2531 return self.mesh.IsQuadratic(id)
2533 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2534 # @ingroup l1_meshinfo
2535 def GetBallDiameter(self, id):
2536 return self.mesh.GetBallDiameter(id)
2538 ## Returns XYZ coordinates of the barycenter of the given element
2539 # \n If there is no element for the given ID - returns an empty list
2540 # @return a list of three double values
2541 # @ingroup l1_meshinfo
2542 def BaryCenter(self, id):
2543 return self.mesh.BaryCenter(id)
2545 ## Passes mesh elements through the given filter and return IDs of fitting elements
2546 # @param theFilter SMESH_Filter
2547 # @return a list of ids
2548 # @ingroup l1_controls
2549 def GetIdsFromFilter(self, theFilter):
2550 theFilter.SetMesh( self.mesh )
2551 return theFilter.GetIDs()
2553 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2554 # Returns a list of special structures (borders).
2555 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2556 # @ingroup l1_controls
2557 def GetFreeBorders(self):
2558 aFilterMgr = self.smeshpyD.CreateFilterManager()
2559 aPredicate = aFilterMgr.CreateFreeEdges()
2560 aPredicate.SetMesh(self.mesh)
2561 aBorders = aPredicate.GetBorders()
2562 aFilterMgr.UnRegister()
2566 # Get mesh measurements information:
2567 # ------------------------------------
2569 ## Get minimum distance between two nodes, elements or distance to the origin
2570 # @param id1 first node/element id
2571 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2572 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2573 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2574 # @return minimum distance value
2575 # @sa GetMinDistance()
2576 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2577 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2578 return aMeasure.value
2580 ## Get measure structure specifying minimum distance data between two objects
2581 # @param id1 first node/element id
2582 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2583 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2584 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2585 # @return Measure structure
2587 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2589 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2591 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2594 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2596 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2601 aMeasurements = self.smeshpyD.CreateMeasurements()
2602 aMeasure = aMeasurements.MinDistance(id1, id2)
2603 genObjUnRegister([aMeasurements,id1, id2])
2606 ## Get bounding box of the specified object(s)
2607 # @param objects single source object or list of source objects or list of nodes/elements IDs
2608 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2609 # @c False specifies that @a objects are nodes
2610 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2611 # @sa GetBoundingBox()
2612 def BoundingBox(self, objects=None, isElem=False):
2613 result = self.GetBoundingBox(objects, isElem)
2617 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2620 ## Get measure structure specifying bounding box data of the specified object(s)
2621 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2622 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2623 # @c False specifies that @a objects are nodes
2624 # @return Measure structure
2626 def GetBoundingBox(self, IDs=None, isElem=False):
2629 elif isinstance(IDs, tuple):
2631 if not isinstance(IDs, list):
2633 if len(IDs) > 0 and isinstance(IDs[0], int):
2636 unRegister = genObjUnRegister()
2638 if isinstance(o, Mesh):
2639 srclist.append(o.mesh)
2640 elif hasattr(o, "_narrow"):
2641 src = o._narrow(SMESH.SMESH_IDSource)
2642 if src: srclist.append(src)
2644 elif isinstance(o, list):
2646 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2648 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2649 unRegister.set( srclist[-1] )
2652 aMeasurements = self.smeshpyD.CreateMeasurements()
2653 unRegister.set( aMeasurements )
2654 aMeasure = aMeasurements.BoundingBox(srclist)
2657 # Mesh edition (SMESH_MeshEditor functionality):
2658 # ---------------------------------------------
2660 ## Removes the elements from the mesh by ids
2661 # @param IDsOfElements is a list of ids of elements to remove
2662 # @return True or False
2663 # @ingroup l2_modif_del
2664 def RemoveElements(self, IDsOfElements):
2665 return self.editor.RemoveElements(IDsOfElements)
2667 ## Removes nodes from mesh by ids
2668 # @param IDsOfNodes is a list of ids of nodes to remove
2669 # @return True or False
2670 # @ingroup l2_modif_del
2671 def RemoveNodes(self, IDsOfNodes):
2672 return self.editor.RemoveNodes(IDsOfNodes)
2674 ## Removes all orphan (free) nodes from mesh
2675 # @return number of the removed nodes
2676 # @ingroup l2_modif_del
2677 def RemoveOrphanNodes(self):
2678 return self.editor.RemoveOrphanNodes()
2680 ## Add a node to the mesh by coordinates
2681 # @return Id of the new node
2682 # @ingroup l2_modif_add
2683 def AddNode(self, x, y, z):
2684 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2685 if hasVars: self.mesh.SetParameters(Parameters)
2686 return self.editor.AddNode( x, y, z)
2688 ## Creates a 0D element on a node with given number.
2689 # @param IDOfNode the ID of node for creation of the element.
2690 # @return the Id of the new 0D element
2691 # @ingroup l2_modif_add
2692 def Add0DElement(self, IDOfNode):
2693 return self.editor.Add0DElement(IDOfNode)
2695 ## Create 0D elements on all nodes of the given elements except those
2696 # nodes on which a 0D element already exists.
2697 # @param theObject an object on whose nodes 0D elements will be created.
2698 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2699 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2700 # @param theGroupName optional name of a group to add 0D elements created
2701 # and/or found on nodes of \a theObject.
2702 # @return an object (a new group or a temporary SMESH_IDSource) holding
2703 # IDs of new and/or found 0D elements. IDs of 0D elements
2704 # can be retrieved from the returned object by calling GetIDs()
2705 # @ingroup l2_modif_add
2706 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2707 unRegister = genObjUnRegister()
2708 if isinstance( theObject, Mesh ):
2709 theObject = theObject.GetMesh()
2710 if isinstance( theObject, list ):
2711 theObject = self.GetIDSource( theObject, SMESH.ALL )
2712 unRegister.set( theObject )
2713 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2715 ## Creates a ball element on a node with given ID.
2716 # @param IDOfNode the ID of node for creation of the element.
2717 # @param diameter the bal diameter.
2718 # @return the Id of the new ball element
2719 # @ingroup l2_modif_add
2720 def AddBall(self, IDOfNode, diameter):
2721 return self.editor.AddBall( IDOfNode, diameter )
2723 ## Creates a linear or quadratic edge (this is determined
2724 # by the number of given nodes).
2725 # @param IDsOfNodes the list of node IDs for creation of the element.
2726 # The order of nodes in this list should correspond to the description
2727 # of MED. \n This description is located by the following link:
2728 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2729 # @return the Id of the new edge
2730 # @ingroup l2_modif_add
2731 def AddEdge(self, IDsOfNodes):
2732 return self.editor.AddEdge(IDsOfNodes)
2734 ## Creates a linear or quadratic face (this is determined
2735 # by the number of given nodes).
2736 # @param IDsOfNodes the list of node IDs for creation of the element.
2737 # The order of nodes in this list should correspond to the description
2738 # of MED. \n This description is located by the following link:
2739 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2740 # @return the Id of the new face
2741 # @ingroup l2_modif_add
2742 def AddFace(self, IDsOfNodes):
2743 return self.editor.AddFace(IDsOfNodes)
2745 ## Adds a polygonal face to the mesh by the list of node IDs
2746 # @param IdsOfNodes the list of node IDs for creation of the element.
2747 # @return the Id of the new face
2748 # @ingroup l2_modif_add
2749 def AddPolygonalFace(self, IdsOfNodes):
2750 return self.editor.AddPolygonalFace(IdsOfNodes)
2752 ## Creates both simple and quadratic volume (this is determined
2753 # by the number of given nodes).
2754 # @param IDsOfNodes the list of node IDs for creation of the element.
2755 # The order of nodes in this list should correspond to the description
2756 # of MED. \n This description is located by the following link:
2757 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2758 # @return the Id of the new volumic element
2759 # @ingroup l2_modif_add
2760 def AddVolume(self, IDsOfNodes):
2761 return self.editor.AddVolume(IDsOfNodes)
2763 ## Creates a volume of many faces, giving nodes for each face.
2764 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2765 # @param Quantities the list of integer values, Quantities[i]
2766 # gives the quantity of nodes in face number i.
2767 # @return the Id of the new volumic element
2768 # @ingroup l2_modif_add
2769 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2770 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2772 ## Creates a volume of many faces, giving the IDs of the existing faces.
2773 # @param IdsOfFaces the list of face IDs for volume creation.
2775 # Note: The created volume will refer only to the nodes
2776 # of the given faces, not to the faces themselves.
2777 # @return the Id of the new volumic element
2778 # @ingroup l2_modif_add
2779 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2780 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2783 ## @brief Binds a node to a vertex
2784 # @param NodeID a node ID
2785 # @param Vertex a vertex or vertex ID
2786 # @return True if succeed else raises an exception
2787 # @ingroup l2_modif_add
2788 def SetNodeOnVertex(self, NodeID, Vertex):
2789 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2790 VertexID = Vertex.GetSubShapeIndices()[0]
2794 self.editor.SetNodeOnVertex(NodeID, VertexID)
2795 except SALOME.SALOME_Exception, inst:
2796 raise ValueError, inst.details.text
2800 ## @brief Stores the node position on an edge
2801 # @param NodeID a node ID
2802 # @param Edge an edge or edge ID
2803 # @param paramOnEdge a parameter on the edge where the node is located
2804 # @return True if succeed else raises an exception
2805 # @ingroup l2_modif_add
2806 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2807 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2808 EdgeID = Edge.GetSubShapeIndices()[0]
2812 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2813 except SALOME.SALOME_Exception, inst:
2814 raise ValueError, inst.details.text
2817 ## @brief Stores node position on a face
2818 # @param NodeID a node ID
2819 # @param Face a face or face ID
2820 # @param u U parameter on the face where the node is located
2821 # @param v V parameter on the face where the node is located
2822 # @return True if succeed else raises an exception
2823 # @ingroup l2_modif_add
2824 def SetNodeOnFace(self, NodeID, Face, u, v):
2825 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2826 FaceID = Face.GetSubShapeIndices()[0]
2830 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2831 except SALOME.SALOME_Exception, inst:
2832 raise ValueError, inst.details.text
2835 ## @brief Binds a node to a solid
2836 # @param NodeID a node ID
2837 # @param Solid a solid or solid ID
2838 # @return True if succeed else raises an exception
2839 # @ingroup l2_modif_add
2840 def SetNodeInVolume(self, NodeID, Solid):
2841 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2842 SolidID = Solid.GetSubShapeIndices()[0]
2846 self.editor.SetNodeInVolume(NodeID, SolidID)
2847 except SALOME.SALOME_Exception, inst:
2848 raise ValueError, inst.details.text
2851 ## @brief Bind an element to a shape
2852 # @param ElementID an element ID
2853 # @param Shape a shape or shape ID
2854 # @return True if succeed else raises an exception
2855 # @ingroup l2_modif_add
2856 def SetMeshElementOnShape(self, ElementID, Shape):
2857 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2858 ShapeID = Shape.GetSubShapeIndices()[0]
2862 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2863 except SALOME.SALOME_Exception, inst:
2864 raise ValueError, inst.details.text
2868 ## Moves the node with the given id
2869 # @param NodeID the id of the node
2870 # @param x a new X coordinate
2871 # @param y a new Y coordinate
2872 # @param z a new Z coordinate
2873 # @return True if succeed else False
2874 # @ingroup l2_modif_movenode
2875 def MoveNode(self, NodeID, x, y, z):
2876 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2877 if hasVars: self.mesh.SetParameters(Parameters)
2878 return self.editor.MoveNode(NodeID, x, y, z)
2880 ## Finds the node closest to a point and moves it to a point location
2881 # @param x the X coordinate of a point
2882 # @param y the Y coordinate of a point
2883 # @param z the Z coordinate of a point
2884 # @param NodeID if specified (>0), the node with this ID is moved,
2885 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2886 # @return the ID of a node
2887 # @ingroup l2_modif_throughp
2888 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2889 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2890 if hasVars: self.mesh.SetParameters(Parameters)
2891 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2893 ## Finds the node closest to a point
2894 # @param x the X coordinate of a point
2895 # @param y the Y coordinate of a point
2896 # @param z the Z coordinate of a point
2897 # @return the ID of a node
2898 # @ingroup l2_modif_throughp
2899 def FindNodeClosestTo(self, x, y, z):
2900 #preview = self.mesh.GetMeshEditPreviewer()
2901 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2902 return self.editor.FindNodeClosestTo(x, y, z)
2904 ## Finds the elements where a point lays IN or ON
2905 # @param x the X coordinate of a point
2906 # @param y the Y coordinate of a point
2907 # @param z the Z coordinate of a point
2908 # @param elementType type of elements to find (SMESH.ALL type
2909 # means elements of any type excluding nodes, discrete and 0D elements)
2910 # @param meshPart a part of mesh (group, sub-mesh) to search within
2911 # @return list of IDs of found elements
2912 # @ingroup l2_modif_throughp
2913 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2915 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2917 return self.editor.FindElementsByPoint(x, y, z, elementType)
2919 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2920 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2921 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2923 def GetPointState(self, x, y, z):
2924 return self.editor.GetPointState(x, y, z)
2926 ## Finds the node closest to a point and moves it to a point location
2927 # @param x the X coordinate of a point
2928 # @param y the Y coordinate of a point
2929 # @param z the Z coordinate of a point
2930 # @return the ID of a moved node
2931 # @ingroup l2_modif_throughp
2932 def MeshToPassThroughAPoint(self, x, y, z):
2933 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2935 ## Replaces two neighbour triangles sharing Node1-Node2 link
2936 # with the triangles built on the same 4 nodes but having other common link.
2937 # @param NodeID1 the ID of the first node
2938 # @param NodeID2 the ID of the second node
2939 # @return false if proper faces were not found
2940 # @ingroup l2_modif_invdiag
2941 def InverseDiag(self, NodeID1, NodeID2):
2942 return self.editor.InverseDiag(NodeID1, NodeID2)
2944 ## Replaces two neighbour triangles sharing Node1-Node2 link
2945 # with a quadrangle built on the same 4 nodes.
2946 # @param NodeID1 the ID of the first node
2947 # @param NodeID2 the ID of the second node
2948 # @return false if proper faces were not found
2949 # @ingroup l2_modif_unitetri
2950 def DeleteDiag(self, NodeID1, NodeID2):
2951 return self.editor.DeleteDiag(NodeID1, NodeID2)
2953 ## Reorients elements by ids
2954 # @param IDsOfElements if undefined reorients all mesh elements
2955 # @return True if succeed else False
2956 # @ingroup l2_modif_changori
2957 def Reorient(self, IDsOfElements=None):
2958 if IDsOfElements == None:
2959 IDsOfElements = self.GetElementsId()
2960 return self.editor.Reorient(IDsOfElements)
2962 ## Reorients all elements of the object
2963 # @param theObject mesh, submesh or group
2964 # @return True if succeed else False
2965 # @ingroup l2_modif_changori
2966 def ReorientObject(self, theObject):
2967 if ( isinstance( theObject, Mesh )):
2968 theObject = theObject.GetMesh()
2969 return self.editor.ReorientObject(theObject)
2971 ## Reorient faces contained in \a the2DObject.
2972 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2973 # @param theDirection is a desired direction of normal of \a theFace.
2974 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2975 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2976 # compared with theDirection. It can be either ID of face or a point
2977 # by which the face will be found. The point can be given as either
2978 # a GEOM vertex or a list of point coordinates.
2979 # @return number of reoriented faces
2980 # @ingroup l2_modif_changori
2981 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2982 unRegister = genObjUnRegister()
2984 if isinstance( the2DObject, Mesh ):
2985 the2DObject = the2DObject.GetMesh()
2986 if isinstance( the2DObject, list ):
2987 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2988 unRegister.set( the2DObject )
2989 # check theDirection
2990 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2991 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2992 if isinstance( theDirection, list ):
2993 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2994 # prepare theFace and thePoint
2995 theFace = theFaceOrPoint
2996 thePoint = PointStruct(0,0,0)
2997 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2998 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3000 if isinstance( theFaceOrPoint, list ):
3001 thePoint = PointStruct( *theFaceOrPoint )
3003 if isinstance( theFaceOrPoint, PointStruct ):
3004 thePoint = theFaceOrPoint
3006 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3008 ## Reorient faces according to adjacent volumes.
3009 # @param the2DObject is a mesh, sub-mesh, group or list of
3010 # either IDs of faces or face groups.
3011 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3012 # @param theOutsideNormal to orient faces to have their normals
3013 # pointing either \a outside or \a inside the adjacent volumes.
3014 # @return number of reoriented faces.
3015 # @ingroup l2_modif_changori
3016 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3017 unRegister = genObjUnRegister()
3019 if not isinstance( the2DObject, list ):
3020 the2DObject = [ the2DObject ]
3021 elif the2DObject and isinstance( the2DObject[0], int ):
3022 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3023 unRegister.set( the2DObject )
3024 the2DObject = [ the2DObject ]
3025 for i,obj2D in enumerate( the2DObject ):
3026 if isinstance( obj2D, Mesh ):
3027 the2DObject[i] = obj2D.GetMesh()
3028 if isinstance( obj2D, list ):
3029 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3030 unRegister.set( the2DObject[i] )
3032 if isinstance( the3DObject, Mesh ):
3033 the3DObject = the3DObject.GetMesh()
3034 if isinstance( the3DObject, list ):
3035 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3036 unRegister.set( the3DObject )
3037 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3039 ## Fuses the neighbouring triangles into quadrangles.
3040 # @param IDsOfElements The triangles to be fused,
3041 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3042 # choose a neighbour to fuse with.
3043 # @param MaxAngle is the maximum angle between element normals at which the fusion
3044 # is still performed; theMaxAngle is mesured in radians.
3045 # Also it could be a name of variable which defines angle in degrees.
3046 # @return TRUE in case of success, FALSE otherwise.
3047 # @ingroup l2_modif_unitetri
3048 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3049 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3050 self.mesh.SetParameters(Parameters)
3051 if not IDsOfElements:
3052 IDsOfElements = self.GetElementsId()
3053 Functor = self.smeshpyD.GetFunctor(theCriterion)
3054 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3056 ## Fuses the neighbouring triangles of the object into quadrangles
3057 # @param theObject is mesh, submesh or group
3058 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3059 # choose a neighbour to fuse with.
3060 # @param MaxAngle a max angle between element normals at which the fusion
3061 # is still performed; theMaxAngle is mesured in radians.
3062 # @return TRUE in case of success, FALSE otherwise.
3063 # @ingroup l2_modif_unitetri
3064 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3065 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3066 self.mesh.SetParameters(Parameters)
3067 if isinstance( theObject, Mesh ):
3068 theObject = theObject.GetMesh()
3069 Functor = self.smeshpyD.GetFunctor(theCriterion)
3070 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3072 ## Splits quadrangles into triangles.
3073 # @param IDsOfElements the faces to be splitted.
3074 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3075 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3076 # value, then quadrangles will be split by the smallest diagonal.
3077 # @return TRUE in case of success, FALSE otherwise.
3078 # @ingroup l2_modif_cutquadr
3079 def QuadToTri (self, IDsOfElements, theCriterion = None):
3080 if IDsOfElements == []:
3081 IDsOfElements = self.GetElementsId()
3082 if theCriterion is None:
3083 theCriterion = FT_MaxElementLength2D
3084 Functor = self.smeshpyD.GetFunctor(theCriterion)
3085 return self.editor.QuadToTri(IDsOfElements, Functor)
3087 ## Splits quadrangles into triangles.
3088 # @param theObject the object from which the list of elements is taken,
3089 # this is mesh, submesh or group
3090 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3091 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3092 # value, then quadrangles will be split by the smallest diagonal.
3093 # @return TRUE in case of success, FALSE otherwise.
3094 # @ingroup l2_modif_cutquadr
3095 def QuadToTriObject (self, theObject, theCriterion = None):
3096 if ( isinstance( theObject, Mesh )):
3097 theObject = theObject.GetMesh()
3098 if theCriterion is None:
3099 theCriterion = FT_MaxElementLength2D
3100 Functor = self.smeshpyD.GetFunctor(theCriterion)
3101 return self.editor.QuadToTriObject(theObject, Functor)
3103 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3105 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3106 # group or a list of face IDs. By default all quadrangles are split
3107 # @ingroup l2_modif_cutquadr
3108 def QuadTo4Tri (self, theElements=[]):
3109 unRegister = genObjUnRegister()
3110 if isinstance( theElements, Mesh ):
3111 theElements = theElements.mesh
3112 elif not theElements:
3113 theElements = self.mesh
3114 elif isinstance( theElements, list ):
3115 theElements = self.GetIDSource( theElements, SMESH.FACE )
3116 unRegister.set( theElements )
3117 return self.editor.QuadTo4Tri( theElements )
3119 ## Splits quadrangles into triangles.
3120 # @param IDsOfElements the faces to be splitted
3121 # @param Diag13 is used to choose a diagonal for splitting.
3122 # @return TRUE in case of success, FALSE otherwise.
3123 # @ingroup l2_modif_cutquadr
3124 def SplitQuad (self, IDsOfElements, Diag13):
3125 if IDsOfElements == []:
3126 IDsOfElements = self.GetElementsId()
3127 return self.editor.SplitQuad(IDsOfElements, Diag13)
3129 ## Splits quadrangles into triangles.
3130 # @param theObject the object from which the list of elements is taken,
3131 # this is mesh, submesh or group
3132 # @param Diag13 is used to choose a diagonal for splitting.
3133 # @return TRUE in case of success, FALSE otherwise.
3134 # @ingroup l2_modif_cutquadr
3135 def SplitQuadObject (self, theObject, Diag13):
3136 if ( isinstance( theObject, Mesh )):
3137 theObject = theObject.GetMesh()
3138 return self.editor.SplitQuadObject(theObject, Diag13)
3140 ## Finds a better splitting of the given quadrangle.
3141 # @param IDOfQuad the ID of the quadrangle to be splitted.
3142 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3143 # choose a diagonal for splitting.
3144 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3145 # diagonal is better, 0 if error occurs.
3146 # @ingroup l2_modif_cutquadr
3147 def BestSplit (self, IDOfQuad, theCriterion):
3148 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3150 ## Splits volumic elements into tetrahedrons
3151 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3152 # @param method flags passing splitting method:
3153 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3154 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3155 # @ingroup l2_modif_cutquadr
3156 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3157 unRegister = genObjUnRegister()
3158 if isinstance( elems, Mesh ):
3159 elems = elems.GetMesh()
3160 if ( isinstance( elems, list )):
3161 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3162 unRegister.set( elems )
3163 self.editor.SplitVolumesIntoTetra(elems, method)
3165 ## Splits hexahedra into prisms
3166 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3167 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3168 # gives a normal vector defining facets to split into triangles.
3169 # @a startHexPoint can be either a triple of coordinates or a vertex.
3170 # @param facetNormal a normal to a facet to split into triangles of a
3171 # hexahedron found by @a startHexPoint.
3172 # @a facetNormal can be either a triple of coordinates or an edge.
3173 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3174 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3175 # @param allDomains if @c False, only hexahedra adjacent to one closest
3176 # to @a startHexPoint are split, else @a startHexPoint
3177 # is used to find the facet to split in all domains present in @a elems.
3178 # @ingroup l2_modif_cutquadr
3179 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3180 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3182 unRegister = genObjUnRegister()
3183 if isinstance( elems, Mesh ):
3184 elems = elems.GetMesh()
3185 if ( isinstance( elems, list )):
3186 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3187 unRegister.set( elems )
3190 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3191 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3192 elif isinstance( startHexPoint, list ):
3193 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3196 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3197 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3198 elif isinstance( facetNormal, list ):
3199 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3202 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3204 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3206 ## Splits quadrangle faces near triangular facets of volumes
3208 # @ingroup l1_auxiliary
3209 def SplitQuadsNearTriangularFacets(self):
3210 faces_array = self.GetElementsByType(SMESH.FACE)
3211 for face_id in faces_array:
3212 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3213 quad_nodes = self.mesh.GetElemNodes(face_id)
3214 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3215 isVolumeFound = False
3216 for node1_elem in node1_elems:
3217 if not isVolumeFound:
3218 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3219 nb_nodes = self.GetElemNbNodes(node1_elem)
3220 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3221 volume_elem = node1_elem
3222 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3223 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3224 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3225 isVolumeFound = True
3226 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3227 self.SplitQuad([face_id], False) # diagonal 2-4
3228 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3229 isVolumeFound = True
3230 self.SplitQuad([face_id], True) # diagonal 1-3
3231 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3232 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3233 isVolumeFound = True
3234 self.SplitQuad([face_id], True) # diagonal 1-3
3236 ## @brief Splits hexahedrons into tetrahedrons.
3238 # This operation uses pattern mapping functionality for splitting.
3239 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3240 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3241 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3242 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3243 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3244 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3245 # @return TRUE in case of success, FALSE otherwise.
3246 # @ingroup l1_auxiliary
3247 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3248 # Pattern: 5.---------.6
3253 # (0,0,1) 4.---------.7 * |
3260 # (0,0,0) 0.---------.3
3261 pattern_tetra = "!!! Nb of points: \n 8 \n\
3271 !!! Indices of points of 6 tetras: \n\
3279 pattern = self.smeshpyD.GetPattern()
3280 isDone = pattern.LoadFromFile(pattern_tetra)
3282 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3285 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3286 isDone = pattern.MakeMesh(self.mesh, False, False)
3287 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3289 # split quafrangle faces near triangular facets of volumes
3290 self.SplitQuadsNearTriangularFacets()
3294 ## @brief Split hexahedrons into prisms.
3296 # Uses the pattern mapping functionality for splitting.
3297 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3298 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3299 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3300 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3301 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3302 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3303 # @return TRUE in case of success, FALSE otherwise.
3304 # @ingroup l1_auxiliary
3305 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3306 # Pattern: 5.---------.6
3311 # (0,0,1) 4.---------.7 |
3318 # (0,0,0) 0.---------.3
3319 pattern_prism = "!!! Nb of points: \n 8 \n\
3329 !!! Indices of points of 2 prisms: \n\
3333 pattern = self.smeshpyD.GetPattern()
3334 isDone = pattern.LoadFromFile(pattern_prism)
3336 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3339 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3340 isDone = pattern.MakeMesh(self.mesh, False, False)
3341 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3343 # Splits quafrangle faces near triangular facets of volumes
3344 self.SplitQuadsNearTriangularFacets()
3348 ## Smoothes elements
3349 # @param IDsOfElements the list if ids of elements to smooth
3350 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3351 # Note that nodes built on edges and boundary nodes are always fixed.
3352 # @param MaxNbOfIterations the maximum number of iterations
3353 # @param MaxAspectRatio varies in range [1.0, inf]
3354 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3355 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3356 # @return TRUE in case of success, FALSE otherwise.
3357 # @ingroup l2_modif_smooth
3358 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3359 MaxNbOfIterations, MaxAspectRatio, Method):
3360 if IDsOfElements == []:
3361 IDsOfElements = self.GetElementsId()
3362 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3363 self.mesh.SetParameters(Parameters)
3364 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3365 MaxNbOfIterations, MaxAspectRatio, Method)
3367 ## Smoothes elements which belong to the given object
3368 # @param theObject the object to smooth
3369 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3370 # Note that nodes built on edges and boundary nodes are always fixed.
3371 # @param MaxNbOfIterations the maximum number of iterations
3372 # @param MaxAspectRatio varies in range [1.0, inf]
3373 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3374 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3375 # @return TRUE in case of success, FALSE otherwise.
3376 # @ingroup l2_modif_smooth
3377 def SmoothObject(self, theObject, IDsOfFixedNodes,
3378 MaxNbOfIterations, MaxAspectRatio, Method):
3379 if ( isinstance( theObject, Mesh )):
3380 theObject = theObject.GetMesh()
3381 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3382 MaxNbOfIterations, MaxAspectRatio, Method)
3384 ## Parametrically smoothes the given elements
3385 # @param IDsOfElements the list if ids of elements to smooth
3386 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3387 # Note that nodes built on edges and boundary nodes are always fixed.
3388 # @param MaxNbOfIterations the maximum number of iterations
3389 # @param MaxAspectRatio varies in range [1.0, inf]
3390 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3391 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3392 # @return TRUE in case of success, FALSE otherwise.
3393 # @ingroup l2_modif_smooth
3394 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3395 MaxNbOfIterations, MaxAspectRatio, Method):
3396 if IDsOfElements == []:
3397 IDsOfElements = self.GetElementsId()
3398 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3399 self.mesh.SetParameters(Parameters)
3400 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3401 MaxNbOfIterations, MaxAspectRatio, Method)
3403 ## Parametrically smoothes the elements which belong to the given object
3404 # @param theObject the object to smooth
3405 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3406 # Note that nodes built on edges and boundary nodes are always fixed.
3407 # @param MaxNbOfIterations the maximum number of iterations
3408 # @param MaxAspectRatio varies in range [1.0, inf]
3409 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3410 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3411 # @return TRUE in case of success, FALSE otherwise.
3412 # @ingroup l2_modif_smooth
3413 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3414 MaxNbOfIterations, MaxAspectRatio, Method):
3415 if ( isinstance( theObject, Mesh )):
3416 theObject = theObject.GetMesh()
3417 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3418 MaxNbOfIterations, MaxAspectRatio, Method)
3420 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3421 # them with quadratic with the same id.
3422 # @param theForce3d new node creation method:
3423 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3424 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3425 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3426 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3427 # @ingroup l2_modif_tofromqu
3428 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3429 if isinstance( theSubMesh, Mesh ):
3430 theSubMesh = theSubMesh.mesh
3432 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3435 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3437 self.editor.ConvertToQuadratic(theForce3d)
3438 error = self.editor.GetLastError()
3439 if error and error.comment:
3442 ## Converts the mesh from quadratic to ordinary,
3443 # deletes old quadratic elements, \n replacing
3444 # them with ordinary mesh elements with the same id.
3445 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3446 # @ingroup l2_modif_tofromqu
3447 def ConvertFromQuadratic(self, theSubMesh=None):
3449 self.editor.ConvertFromQuadraticObject(theSubMesh)
3451 return self.editor.ConvertFromQuadratic()
3453 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3454 # @return TRUE if operation has been completed successfully, FALSE otherwise
3455 # @ingroup l2_modif_edit
3456 def Make2DMeshFrom3D(self):
3457 return self.editor. Make2DMeshFrom3D()
3459 ## Creates missing boundary elements
3460 # @param elements - elements whose boundary is to be checked:
3461 # mesh, group, sub-mesh or list of elements
3462 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3463 # @param dimension - defines type of boundary elements to create:
3464 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3465 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3466 # @param groupName - a name of group to store created boundary elements in,
3467 # "" means not to create the group
3468 # @param meshName - a name of new mesh to store created boundary elements in,
3469 # "" means not to create the new mesh
3470 # @param toCopyElements - if true, the checked elements will be copied into
3471 # the new mesh else only boundary elements will be copied into the new mesh
3472 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3473 # boundary elements will be copied into the new mesh
3474 # @return tuple (mesh, group) where boundary elements were added to
3475 # @ingroup l2_modif_edit
3476 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3477 toCopyElements=False, toCopyExistingBondary=False):
3478 unRegister = genObjUnRegister()
3479 if isinstance( elements, Mesh ):
3480 elements = elements.GetMesh()
3481 if ( isinstance( elements, list )):
3482 elemType = SMESH.ALL
3483 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3484 elements = self.editor.MakeIDSource(elements, elemType)
3485 unRegister.set( elements )
3486 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3487 toCopyElements,toCopyExistingBondary)
3488 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3492 # @brief Creates missing boundary elements around either the whole mesh or
3493 # groups of elements
3494 # @param dimension - defines type of boundary elements to create
3495 # @param groupName - a name of group to store all boundary elements in,
3496 # "" means not to create the group
3497 # @param meshName - a name of a new mesh, which is a copy of the initial
3498 # mesh + created boundary elements; "" means not to create the new mesh
3499 # @param toCopyAll - if true, the whole initial mesh will be copied into
3500 # the new mesh else only boundary elements will be copied into the new mesh
3501 # @param groups - groups of elements to make boundary around
3502 # @retval tuple( long, mesh, groups )
3503 # long - number of added boundary elements
3504 # mesh - the mesh where elements were added to
3505 # group - the group of boundary elements or None
3507 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3508 toCopyAll=False, groups=[]):
3509 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3511 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3512 return nb, mesh, group
3514 ## Renumber mesh nodes (Obsolete, does nothing)
3515 # @ingroup l2_modif_renumber
3516 def RenumberNodes(self):
3517 self.editor.RenumberNodes()
3519 ## Renumber mesh elements (Obsole, does nothing)
3520 # @ingroup l2_modif_renumber
3521 def RenumberElements(self):
3522 self.editor.RenumberElements()
3524 ## Private method converting \a arg into a list of SMESH_IdSource's
3525 def _getIdSourceList(self, arg, idType, unRegister):
3526 if arg and isinstance( arg, list ):
3527 if isinstance( arg[0], int ):
3528 arg = self.GetIDSource( arg, idType )
3529 unRegister.set( arg )
3530 elif isinstance( arg[0], Mesh ):
3531 arg[0] = arg[0].GetMesh()
3532 elif isinstance( arg, Mesh ):
3534 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3538 ## Generates new elements by rotation of the given elements and nodes around the axis
3539 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3540 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3541 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3542 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3543 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3544 # which defines angle in degrees
3545 # @param NbOfSteps the number of steps
3546 # @param Tolerance tolerance
3547 # @param MakeGroups forces the generation of new groups from existing ones
3548 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3549 # of all steps, else - size of each step
3550 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3551 # @ingroup l2_modif_extrurev
3552 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3553 MakeGroups=False, TotalAngle=False):
3554 unRegister = genObjUnRegister()
3555 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3556 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3557 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3559 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3560 Axis = self.smeshpyD.GetAxisStruct( Axis )
3561 if isinstance( Axis, list ):
3562 Axis = SMESH.AxisStruct( *Axis )
3564 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3565 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3566 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3567 self.mesh.SetParameters(Parameters)
3568 if TotalAngle and NbOfSteps:
3569 AngleInRadians /= NbOfSteps
3570 return self.editor.RotationSweepObjects( nodes, edges, faces,
3571 Axis, AngleInRadians,
3572 NbOfSteps, Tolerance, MakeGroups)
3574 ## Generates new elements by rotation of the elements around the axis
3575 # @param IDsOfElements the list of ids of elements to sweep
3576 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3577 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3578 # @param NbOfSteps the number of steps
3579 # @param Tolerance tolerance
3580 # @param MakeGroups forces the generation of new groups from existing ones
3581 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3582 # of all steps, else - size of each step
3583 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3584 # @ingroup l2_modif_extrurev
3585 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3586 MakeGroups=False, TotalAngle=False):
3587 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3588 AngleInRadians, NbOfSteps, Tolerance,
3589 MakeGroups, TotalAngle)
3591 ## Generates new elements by rotation of the elements of object around the axis
3592 # @param theObject object which elements should be sweeped.
3593 # It can be a mesh, a sub mesh or a group.
3594 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3595 # @param AngleInRadians the angle of Rotation
3596 # @param NbOfSteps number of steps
3597 # @param Tolerance tolerance
3598 # @param MakeGroups forces the generation of new groups from existing ones
3599 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3600 # of all steps, else - size of each step
3601 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3602 # @ingroup l2_modif_extrurev
3603 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3604 MakeGroups=False, TotalAngle=False):
3605 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3606 AngleInRadians, NbOfSteps, Tolerance,
3607 MakeGroups, TotalAngle )
3609 ## Generates new elements by rotation of the elements of object around the axis
3610 # @param theObject object which elements should be sweeped.
3611 # It can be a mesh, a sub mesh or a group.
3612 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3613 # @param AngleInRadians the angle of Rotation
3614 # @param NbOfSteps number of steps
3615 # @param Tolerance tolerance
3616 # @param MakeGroups forces the generation of new groups from existing ones
3617 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3618 # of all steps, else - size of each step
3619 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3620 # @ingroup l2_modif_extrurev
3621 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3622 MakeGroups=False, TotalAngle=False):
3623 return self.RotationSweepObjects([],theObject,[], Axis,
3624 AngleInRadians, NbOfSteps, Tolerance,
3625 MakeGroups, TotalAngle)
3627 ## Generates new elements by rotation of the elements of object around the axis
3628 # @param theObject object which elements should be sweeped.
3629 # It can be a mesh, a sub mesh or a group.
3630 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3631 # @param AngleInRadians the angle of Rotation
3632 # @param NbOfSteps number of steps
3633 # @param Tolerance tolerance
3634 # @param MakeGroups forces the generation of new groups from existing ones
3635 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3636 # of all steps, else - size of each step
3637 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3638 # @ingroup l2_modif_extrurev
3639 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3640 MakeGroups=False, TotalAngle=False):
3641 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3642 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3644 ## Generates new elements by extrusion of the given elements and nodes
3645 # @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3646 # @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3647 # @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3648 # @param StepVector vector or DirStruct or 3 vector components, defining
3649 # the direction and value of extrusion for one step (the total extrusion
3650 # length will be NbOfSteps * ||StepVector||)
3651 # @param NbOfSteps the number of steps
3652 # @param MakeGroups forces the generation of new groups from existing ones
3653 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3654 # @ingroup l2_modif_extrurev
3655 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3656 unRegister = genObjUnRegister()
3657 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3658 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3659 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3661 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3662 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3663 if isinstance( StepVector, list ):
3664 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3666 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3667 Parameters = StepVector.PS.parameters + var_separator + Parameters
3668 self.mesh.SetParameters(Parameters)
3670 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3671 StepVector, NbOfSteps, MakeGroups)
3674 ## Generates new elements by extrusion of the elements with given ids
3675 # @param IDsOfElements the list of elements ids for extrusion
3676 # @param StepVector vector or DirStruct or 3 vector components, defining
3677 # the direction and value of extrusion for one step (the total extrusion
3678 # length will be NbOfSteps * ||StepVector||)
3679 # @param NbOfSteps the number of steps
3680 # @param MakeGroups forces the generation of new groups from existing ones
3681 # @param IsNodes is True if elements with given ids are nodes
3682 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3683 # @ingroup l2_modif_extrurev
3684 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3686 if IsNodes: n = IDsOfElements
3687 else : e,f, = IDsOfElements,IDsOfElements
3688 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3690 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3691 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3692 # Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3693 # @param StepSize length of one extrusion step (the total extrusion
3694 # length will be \a NbOfSteps * \a StepSize ).
3695 # @param NbOfSteps number of extrusion steps.
3696 # @param ByAverageNormal if True each node is translated by \a StepSize
3697 # along the average of the normal vectors to the faces sharing the node;
3698 # else each node is translated along the same average normal till
3699 # intersection with the plane got by translation of the face sharing
3700 # the node along its own normal by \a StepSize.
3701 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3702 # for every node of \a Elements.
3703 # @param MakeGroups forces generation of new groups from existing ones.
3704 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3705 # is not yet implemented. This parameter is used if \a Elements contains
3706 # both faces and edges, i.e. \a Elements is a Mesh.
3707 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3708 # empty list otherwise.
3709 # @ingroup l2_modif_extrurev
3710 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3711 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3712 unRegister = genObjUnRegister()
3713 if isinstance( Elements, Mesh ):
3714 Elements = [ Elements.GetMesh() ]
3715 if isinstance( Elements, list ):
3717 raise RuntimeError, "Elements empty!"
3718 if isinstance( Elements[0], int ):
3719 Elements = self.GetIDSource( Elements, SMESH.ALL )
3720 unRegister.set( Elements )
3721 if not isinstance( Elements, list ):
3722 Elements = [ Elements ]
3723 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3724 self.mesh.SetParameters(Parameters)
3725 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3726 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3728 ## Generates new elements by extrusion of the elements which belong to the object
3729 # @param theObject the object which elements should be processed.
3730 # It can be a mesh, a sub mesh or a group.
3731 # @param StepVector vector or DirStruct or 3 vector components, defining
3732 # the direction and value of extrusion for one step (the total extrusion
3733 # length will be NbOfSteps * ||StepVector||)
3734 # @param NbOfSteps the number of steps
3735 # @param MakeGroups forces the generation of new groups from existing ones
3736 # @param IsNodes is True if elements to extrude are nodes
3737 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3738 # @ingroup l2_modif_extrurev
3739 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3741 if IsNodes: n = theObject
3742 else : e,f, = theObject,theObject
3743 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3745 ## Generates new elements by extrusion of the elements which belong to the object
3746 # @param theObject object which elements should be processed.
3747 # It can be a mesh, a sub mesh or a group.
3748 # @param StepVector vector or DirStruct or 3 vector components, defining
3749 # the direction and value of extrusion for one step (the total extrusion
3750 # length will be NbOfSteps * ||StepVector||)
3751 # @param NbOfSteps the number of steps
3752 # @param MakeGroups to generate new groups from existing ones
3753 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3754 # @ingroup l2_modif_extrurev
3755 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3756 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3758 ## Generates new elements by extrusion of the elements which belong to the object
3759 # @param theObject object which elements should be processed.
3760 # It can be a mesh, a sub mesh or a group.
3761 # @param StepVector vector or DirStruct or 3 vector components, defining
3762 # the direction and value of extrusion for one step (the total extrusion
3763 # length will be NbOfSteps * ||StepVector||)
3764 # @param NbOfSteps the number of steps
3765 # @param MakeGroups forces the generation of new groups from existing ones
3766 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3767 # @ingroup l2_modif_extrurev
3768 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3769 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3771 ## Generates new elements by extrusion of the elements with given ids
3772 # @param IDsOfElements is ids of elements
3773 # @param StepVector vector or DirStruct or 3 vector components, defining
3774 # the direction and value of extrusion for one step (the total extrusion
3775 # length will be NbOfSteps * ||StepVector||)
3776 # @param NbOfSteps the number of steps
3777 # @param ExtrFlags sets flags for extrusion
3778 # @param SewTolerance uses for comparing locations of nodes if flag
3779 # EXTRUSION_FLAG_SEW is set
3780 # @param MakeGroups forces the generation of new groups from existing ones
3781 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3782 # @ingroup l2_modif_extrurev
3783 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3784 ExtrFlags, SewTolerance, MakeGroups=False):
3785 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3786 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3787 if isinstance( StepVector, list ):
3788 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3789 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3790 ExtrFlags, SewTolerance, MakeGroups)
3792 ## Generates new elements by extrusion of the given elements and nodes along the path.
3793 # The path of extrusion must be a meshed edge.
3794 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3795 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3796 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3797 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3798 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3799 # contains not only path segments, else it can be None
3800 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3801 # @param HasAngles allows the shape to be rotated around the path
3802 # to get the resulting mesh in a helical fashion
3803 # @param Angles list of angles
3804 # @param LinearVariation forces the computation of rotation angles as linear
3805 # variation of the given Angles along path steps
3806 # @param HasRefPoint allows using the reference point
3807 # @param RefPoint the point around which the shape is rotated (the mass center of the
3808 # shape by default). The User can specify any point as the Reference Point.
3809 # @param MakeGroups forces the generation of new groups from existing ones
3810 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3811 # @ingroup l2_modif_extrurev
3812 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3813 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3814 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3815 unRegister = genObjUnRegister()
3816 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3817 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3818 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3820 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3821 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3822 if isinstance( RefPoint, list ):
3823 RefPoint = SMESH.PointStruct( *RefPoint )
3824 if isinstance( PathMesh, Mesh ):
3825 PathMesh = PathMesh.GetMesh()
3826 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3827 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3828 self.mesh.SetParameters(Parameters)
3829 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3830 PathMesh, PathShape, NodeStart,
3831 HasAngles, Angles, LinearVariation,
3832 HasRefPoint, RefPoint, MakeGroups)
3834 ## Generates new elements by extrusion of the given elements
3835 # The path of extrusion must be a meshed edge.
3836 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3837 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3838 # @param NodeStart the start node from Path. Defines the direction of extrusion
3839 # @param HasAngles allows the shape to be rotated around the path
3840 # to get the resulting mesh in a helical fashion
3841 # @param Angles list of angles in radians
3842 # @param LinearVariation forces the computation of rotation angles as linear
3843 # variation of the given Angles along path steps
3844 # @param HasRefPoint allows using the reference point
3845 # @param RefPoint the point around which the elements are rotated (the mass
3846 # center of the elements by default).
3847 # The User can specify any point as the Reference Point.
3848 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3849 # @param MakeGroups forces the generation of new groups from existing ones
3850 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3851 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3852 # only SMESH::Extrusion_Error otherwise
3853 # @ingroup l2_modif_extrurev
3854 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3855 HasAngles, Angles, LinearVariation,
3856 HasRefPoint, RefPoint, MakeGroups, ElemType):
3858 if ElemType == SMESH.NODE: n = Base
3859 if ElemType == SMESH.EDGE: e = Base
3860 if ElemType == SMESH.FACE: f = Base
3861 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
3862 HasAngles, Angles, LinearVariation,
3863 HasRefPoint, RefPoint, MakeGroups)
3864 if MakeGroups: return gr,er
3867 ## Generates new elements by extrusion of the given elements
3868 # The path of extrusion must be a meshed edge.
3869 # @param IDsOfElements ids of elements
3870 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3871 # @param PathShape shape(edge) defines the sub-mesh for the path
3872 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3873 # @param HasAngles allows the shape to be rotated around the path
3874 # to get the resulting mesh in a helical fashion
3875 # @param Angles list of angles in radians
3876 # @param HasRefPoint allows using the reference point
3877 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3878 # The User can specify any point as the Reference Point.
3879 # @param MakeGroups forces the generation of new groups from existing ones
3880 # @param LinearVariation forces the computation of rotation angles as linear
3881 # variation of the given Angles along path steps
3882 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3883 # only SMESH::Extrusion_Error otherwise
3884 # @ingroup l2_modif_extrurev
3885 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3886 HasAngles, Angles, HasRefPoint, RefPoint,
3887 MakeGroups=False, LinearVariation=False):
3888 n,e,f = [],IDsOfElements,IDsOfElements
3889 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
3890 NodeStart, HasAngles, Angles,
3892 HasRefPoint, RefPoint, MakeGroups)
3893 if MakeGroups: return gr,er
3896 ## Generates new elements by extrusion of the elements which belong to the object
3897 # The path of extrusion must be a meshed edge.
3898 # @param theObject the object which elements should be processed.
3899 # It can be a mesh, a sub-mesh or a group.
3900 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3901 # @param PathShape shape(edge) defines the sub-mesh for the path
3902 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3903 # @param HasAngles allows the shape to be rotated around the path
3904 # to get the resulting mesh in a helical fashion
3905 # @param Angles list of angles
3906 # @param HasRefPoint allows using the reference point
3907 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3908 # The User can specify any point as the Reference Point.
3909 # @param MakeGroups forces the generation of new groups from existing ones
3910 # @param LinearVariation forces the computation of rotation angles as linear
3911 # variation of the given Angles along path steps
3912 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3913 # only SMESH::Extrusion_Error otherwise
3914 # @ingroup l2_modif_extrurev
3915 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3916 HasAngles, Angles, HasRefPoint, RefPoint,
3917 MakeGroups=False, LinearVariation=False):
3918 n,e,f = [],theObject,theObject
3919 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3920 HasAngles, Angles, LinearVariation,
3921 HasRefPoint, RefPoint, MakeGroups)
3922 if MakeGroups: return gr,er
3925 ## Generates new elements by extrusion of the elements which belong to the object
3926 # The path of extrusion must be a meshed edge.
3927 # @param theObject the object which elements should be processed.
3928 # It can be a mesh, a sub mesh or a group.
3929 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3930 # @param PathShape shape(edge) defines the sub-mesh for the path
3931 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3932 # @param HasAngles allows the shape to be rotated around the path
3933 # to get the resulting mesh in a helical fashion
3934 # @param Angles list of angles
3935 # @param HasRefPoint allows using the reference point
3936 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3937 # The User can specify any point as the Reference Point.
3938 # @param MakeGroups forces the generation of new groups from existing ones
3939 # @param LinearVariation forces the computation of rotation angles as linear
3940 # variation of the given Angles along path steps
3941 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3942 # only SMESH::Extrusion_Error otherwise
3943 # @ingroup l2_modif_extrurev
3944 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3945 HasAngles, Angles, HasRefPoint, RefPoint,
3946 MakeGroups=False, LinearVariation=False):
3947 n,e,f = [],theObject,[]
3948 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3949 HasAngles, Angles, LinearVariation,
3950 HasRefPoint, RefPoint, MakeGroups)
3951 if MakeGroups: return gr,er
3954 ## Generates new elements by extrusion of the elements which belong to the object
3955 # The path of extrusion must be a meshed edge.
3956 # @param theObject the object which elements should be processed.
3957 # It can be a mesh, a sub mesh or a group.
3958 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3959 # @param PathShape shape(edge) defines the sub-mesh for the path
3960 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3961 # @param HasAngles allows the shape to be rotated around the path
3962 # to get the resulting mesh in a helical fashion
3963 # @param Angles list of angles
3964 # @param HasRefPoint allows using the reference point
3965 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3966 # The User can specify any point as the Reference Point.
3967 # @param MakeGroups forces the generation of new groups from existing ones
3968 # @param LinearVariation forces the computation of rotation angles as linear
3969 # variation of the given Angles along path steps
3970 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3971 # only SMESH::Extrusion_Error otherwise
3972 # @ingroup l2_modif_extrurev
3973 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3974 HasAngles, Angles, HasRefPoint, RefPoint,
3975 MakeGroups=False, LinearVariation=False):
3976 n,e,f = [],[],theObject
3977 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
3978 HasAngles, Angles, LinearVariation,
3979 HasRefPoint, RefPoint, MakeGroups)
3980 if MakeGroups: return gr,er
3983 ## Creates a symmetrical copy of mesh elements
3984 # @param IDsOfElements list of elements ids
3985 # @param Mirror is AxisStruct or geom object(point, line, plane)
3986 # @param theMirrorType is POINT, AXIS or PLANE
3987 # If the Mirror is a geom object this parameter is unnecessary
3988 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3989 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3990 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3991 # @ingroup l2_modif_trsf
3992 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
3993 if IDsOfElements == []:
3994 IDsOfElements = self.GetElementsId()
3995 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3996 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3997 theMirrorType = Mirror._mirrorType
3999 self.mesh.SetParameters(Mirror.parameters)
4000 if Copy and MakeGroups:
4001 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4002 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4005 ## Creates a new mesh by a symmetrical copy of mesh elements
4006 # @param IDsOfElements the list of elements ids
4007 # @param Mirror is AxisStruct or geom object (point, line, plane)
4008 # @param theMirrorType is POINT, AXIS or PLANE
4009 # If the Mirror is a geom object this parameter is unnecessary
4010 # @param MakeGroups to generate new groups from existing ones
4011 # @param NewMeshName a name of the new mesh to create
4012 # @return instance of Mesh class
4013 # @ingroup l2_modif_trsf
4014 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4015 if IDsOfElements == []:
4016 IDsOfElements = self.GetElementsId()
4017 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4018 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4019 theMirrorType = Mirror._mirrorType
4021 self.mesh.SetParameters(Mirror.parameters)
4022 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4023 MakeGroups, NewMeshName)
4024 return Mesh(self.smeshpyD,self.geompyD,mesh)
4026 ## Creates a symmetrical copy of the object
4027 # @param theObject mesh, submesh or group
4028 # @param Mirror AxisStruct or geom object (point, line, plane)
4029 # @param theMirrorType is POINT, AXIS or PLANE
4030 # If the Mirror is a geom object this parameter is unnecessary
4031 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4032 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4033 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4034 # @ingroup l2_modif_trsf
4035 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4036 if ( isinstance( theObject, Mesh )):
4037 theObject = theObject.GetMesh()
4038 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4039 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4040 theMirrorType = Mirror._mirrorType
4042 self.mesh.SetParameters(Mirror.parameters)
4043 if Copy and MakeGroups:
4044 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4045 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4048 ## Creates a new mesh by a symmetrical copy of the object
4049 # @param theObject mesh, submesh or group
4050 # @param Mirror AxisStruct or geom object (point, line, plane)
4051 # @param theMirrorType POINT, AXIS or PLANE
4052 # If the Mirror is a geom object this parameter is unnecessary
4053 # @param MakeGroups forces the generation of new groups from existing ones
4054 # @param NewMeshName the name of the new mesh to create
4055 # @return instance of Mesh class
4056 # @ingroup l2_modif_trsf
4057 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4058 if ( isinstance( theObject, Mesh )):
4059 theObject = theObject.GetMesh()
4060 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4061 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4062 theMirrorType = Mirror._mirrorType
4064 self.mesh.SetParameters(Mirror.parameters)
4065 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4066 MakeGroups, NewMeshName)
4067 return Mesh( self.smeshpyD,self.geompyD,mesh )
4069 ## Translates the elements
4070 # @param IDsOfElements list of elements ids
4071 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4072 # @param Copy allows copying the translated elements
4073 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4074 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4075 # @ingroup l2_modif_trsf
4076 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4077 if IDsOfElements == []:
4078 IDsOfElements = self.GetElementsId()
4079 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4080 Vector = self.smeshpyD.GetDirStruct(Vector)
4081 if isinstance( Vector, list ):
4082 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4083 self.mesh.SetParameters(Vector.PS.parameters)
4084 if Copy and MakeGroups:
4085 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4086 self.editor.Translate(IDsOfElements, Vector, Copy)
4089 ## Creates a new mesh of translated elements
4090 # @param IDsOfElements list of elements ids
4091 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4092 # @param MakeGroups forces the generation of new groups from existing ones
4093 # @param NewMeshName the name of the newly created mesh
4094 # @return instance of Mesh class
4095 # @ingroup l2_modif_trsf
4096 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4097 if IDsOfElements == []:
4098 IDsOfElements = self.GetElementsId()
4099 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4100 Vector = self.smeshpyD.GetDirStruct(Vector)
4101 if isinstance( Vector, list ):
4102 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4103 self.mesh.SetParameters(Vector.PS.parameters)
4104 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4105 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4107 ## Translates the object
4108 # @param theObject the object to translate (mesh, submesh, or group)
4109 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4110 # @param Copy allows copying the translated elements
4111 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4112 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4113 # @ingroup l2_modif_trsf
4114 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4115 if ( isinstance( theObject, Mesh )):
4116 theObject = theObject.GetMesh()
4117 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4118 Vector = self.smeshpyD.GetDirStruct(Vector)
4119 if isinstance( Vector, list ):
4120 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4121 self.mesh.SetParameters(Vector.PS.parameters)
4122 if Copy and MakeGroups:
4123 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4124 self.editor.TranslateObject(theObject, Vector, Copy)
4127 ## Creates a new mesh from the translated object
4128 # @param theObject the object to translate (mesh, submesh, or group)
4129 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4130 # @param MakeGroups forces the generation of new groups from existing ones
4131 # @param NewMeshName the name of the newly created mesh
4132 # @return instance of Mesh class
4133 # @ingroup l2_modif_trsf
4134 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4135 if isinstance( theObject, Mesh ):
4136 theObject = theObject.GetMesh()
4137 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4138 Vector = self.smeshpyD.GetDirStruct(Vector)
4139 if isinstance( Vector, list ):
4140 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4141 self.mesh.SetParameters(Vector.PS.parameters)
4142 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4143 return Mesh( self.smeshpyD, self.geompyD, mesh )
4147 ## Scales the object
4148 # @param theObject - the object to translate (mesh, submesh, or group)
4149 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4150 # @param theScaleFact - list of 1-3 scale factors for axises
4151 # @param Copy - allows copying the translated elements
4152 # @param MakeGroups - forces the generation of new groups from existing
4154 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4155 # empty list otherwise
4156 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4157 unRegister = genObjUnRegister()
4158 if ( isinstance( theObject, Mesh )):
4159 theObject = theObject.GetMesh()
4160 if ( isinstance( theObject, list )):
4161 theObject = self.GetIDSource(theObject, SMESH.ALL)
4162 unRegister.set( theObject )
4163 if ( isinstance( thePoint, list )):
4164 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4165 if ( isinstance( theScaleFact, float )):
4166 theScaleFact = [theScaleFact]
4167 if ( isinstance( theScaleFact, int )):
4168 theScaleFact = [ float(theScaleFact)]
4170 self.mesh.SetParameters(thePoint.parameters)
4172 if Copy and MakeGroups:
4173 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4174 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4177 ## Creates a new mesh from the translated object
4178 # @param theObject - the object to translate (mesh, submesh, or group)
4179 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4180 # @param theScaleFact - list of 1-3 scale factors for axises
4181 # @param MakeGroups - forces the generation of new groups from existing ones
4182 # @param NewMeshName - the name of the newly created mesh
4183 # @return instance of Mesh class
4184 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4185 unRegister = genObjUnRegister()
4186 if (isinstance(theObject, Mesh)):
4187 theObject = theObject.GetMesh()
4188 if ( isinstance( theObject, list )):
4189 theObject = self.GetIDSource(theObject,SMESH.ALL)
4190 unRegister.set( theObject )
4191 if ( isinstance( thePoint, list )):
4192 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4193 if ( isinstance( theScaleFact, float )):
4194 theScaleFact = [theScaleFact]
4195 if ( isinstance( theScaleFact, int )):
4196 theScaleFact = [ float(theScaleFact)]
4198 self.mesh.SetParameters(thePoint.parameters)
4199 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4200 MakeGroups, NewMeshName)
4201 return Mesh( self.smeshpyD, self.geompyD, mesh )
4205 ## Rotates the elements
4206 # @param IDsOfElements list of elements ids
4207 # @param Axis the axis of rotation (AxisStruct or geom line)
4208 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4209 # @param Copy allows copying the rotated elements
4210 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4211 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4212 # @ingroup l2_modif_trsf
4213 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4214 if IDsOfElements == []:
4215 IDsOfElements = self.GetElementsId()
4216 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4217 Axis = self.smeshpyD.GetAxisStruct(Axis)
4218 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4219 Parameters = Axis.parameters + var_separator + Parameters
4220 self.mesh.SetParameters(Parameters)
4221 if Copy and MakeGroups:
4222 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4223 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4226 ## Creates a new mesh of rotated elements
4227 # @param IDsOfElements list of element ids
4228 # @param Axis the axis of rotation (AxisStruct or geom line)
4229 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4230 # @param MakeGroups forces the generation of new groups from existing ones
4231 # @param NewMeshName the name of the newly created mesh
4232 # @return instance of Mesh class
4233 # @ingroup l2_modif_trsf
4234 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4235 if IDsOfElements == []:
4236 IDsOfElements = self.GetElementsId()
4237 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4238 Axis = self.smeshpyD.GetAxisStruct(Axis)
4239 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4240 Parameters = Axis.parameters + var_separator + Parameters
4241 self.mesh.SetParameters(Parameters)
4242 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4243 MakeGroups, NewMeshName)
4244 return Mesh( self.smeshpyD, self.geompyD, mesh )
4246 ## Rotates the object
4247 # @param theObject the object to rotate( mesh, submesh, or group)
4248 # @param Axis the axis of rotation (AxisStruct or geom line)
4249 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4250 # @param Copy allows copying the rotated elements
4251 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4252 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4253 # @ingroup l2_modif_trsf
4254 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4255 if (isinstance(theObject, Mesh)):
4256 theObject = theObject.GetMesh()
4257 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4258 Axis = self.smeshpyD.GetAxisStruct(Axis)
4259 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4260 Parameters = Axis.parameters + ":" + Parameters
4261 self.mesh.SetParameters(Parameters)
4262 if Copy and MakeGroups:
4263 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4264 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4267 ## Creates a new mesh from the rotated object
4268 # @param theObject the object to rotate (mesh, submesh, or group)
4269 # @param Axis the axis of rotation (AxisStruct or geom line)
4270 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4271 # @param MakeGroups forces the generation of new groups from existing ones
4272 # @param NewMeshName the name of the newly created mesh
4273 # @return instance of Mesh class
4274 # @ingroup l2_modif_trsf
4275 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4276 if (isinstance( theObject, Mesh )):
4277 theObject = theObject.GetMesh()
4278 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4279 Axis = self.smeshpyD.GetAxisStruct(Axis)
4280 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4281 Parameters = Axis.parameters + ":" + Parameters
4282 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4283 MakeGroups, NewMeshName)
4284 self.mesh.SetParameters(Parameters)
4285 return Mesh( self.smeshpyD, self.geompyD, mesh )
4287 ## Finds groups of adjacent nodes within Tolerance.
4288 # @param Tolerance the value of tolerance
4289 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4290 # @ingroup l2_modif_trsf
4291 def FindCoincidentNodes (self, Tolerance):
4292 return self.editor.FindCoincidentNodes(Tolerance)
4294 ## Finds groups of ajacent nodes within Tolerance.
4295 # @param Tolerance the value of tolerance
4296 # @param SubMeshOrGroup SubMesh or Group
4297 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4298 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4299 # @ingroup l2_modif_trsf
4300 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4301 unRegister = genObjUnRegister()
4302 if (isinstance( SubMeshOrGroup, Mesh )):
4303 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4304 if not isinstance( exceptNodes, list):
4305 exceptNodes = [ exceptNodes ]
4306 if exceptNodes and isinstance( exceptNodes[0], int):
4307 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4308 unRegister.set( exceptNodes )
4309 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4312 # @param GroupsOfNodes a list of pairs of nodes IDs for merging
4313 # (e.g. [[1,12],[25,4]], then nodes 12 and 4 will be removed and replaced
4314 # by nodes 1 and 25 correspondingly in all elements and groups
4315 # @ingroup l2_modif_trsf
4316 def MergeNodes (self, GroupsOfNodes):
4317 self.editor.MergeNodes(GroupsOfNodes)
4319 ## Finds the elements built on the same nodes.
4320 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4321 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4322 # @ingroup l2_modif_trsf
4323 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4324 if not MeshOrSubMeshOrGroup:
4325 MeshOrSubMeshOrGroup=self.mesh
4326 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4327 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4328 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4330 ## Merges elements in each given group.
4331 # @param GroupsOfElementsID a list of pairs of elements IDs for merging
4332 # (e.g. [[1,12],[25,4]], then elements 12 and 4 will be removed and
4333 # replaced by elements 1 and 25 in all groups)
4334 # @ingroup l2_modif_trsf
4335 def MergeElements(self, GroupsOfElementsID):
4336 self.editor.MergeElements(GroupsOfElementsID)
4338 ## Leaves one element and removes all other elements built on the same nodes.
4339 # @ingroup l2_modif_trsf
4340 def MergeEqualElements(self):
4341 self.editor.MergeEqualElements()
4343 ## Sews free borders
4344 # @return SMESH::Sew_Error
4345 # @ingroup l2_modif_trsf
4346 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4347 FirstNodeID2, SecondNodeID2, LastNodeID2,
4348 CreatePolygons, CreatePolyedrs):
4349 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4350 FirstNodeID2, SecondNodeID2, LastNodeID2,
4351 CreatePolygons, CreatePolyedrs)
4353 ## Sews conform free borders
4354 # @return SMESH::Sew_Error
4355 # @ingroup l2_modif_trsf
4356 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4357 FirstNodeID2, SecondNodeID2):
4358 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4359 FirstNodeID2, SecondNodeID2)
4361 ## Sews border to side
4362 # @return SMESH::Sew_Error
4363 # @ingroup l2_modif_trsf
4364 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4365 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4366 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4367 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4369 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4370 # merged with the nodes of elements of Side2.
4371 # The number of elements in theSide1 and in theSide2 must be
4372 # equal and they should have similar nodal connectivity.
4373 # The nodes to merge should belong to side borders and
4374 # the first node should be linked to the second.
4375 # @return SMESH::Sew_Error
4376 # @ingroup l2_modif_trsf
4377 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4378 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4379 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4380 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4381 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4382 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4384 ## Sets new nodes for the given element.
4385 # @param ide the element id
4386 # @param newIDs nodes ids
4387 # @return If the number of nodes does not correspond to the type of element - returns false
4388 # @ingroup l2_modif_edit
4389 def ChangeElemNodes(self, ide, newIDs):
4390 return self.editor.ChangeElemNodes(ide, newIDs)
4392 ## If during the last operation of MeshEditor some nodes were
4393 # created, this method returns the list of their IDs, \n
4394 # if new nodes were not created - returns empty list
4395 # @return the list of integer values (can be empty)
4396 # @ingroup l1_auxiliary
4397 def GetLastCreatedNodes(self):
4398 return self.editor.GetLastCreatedNodes()
4400 ## If during the last operation of MeshEditor some elements were
4401 # created this method returns the list of their IDs, \n
4402 # if new elements were not created - returns empty list
4403 # @return the list of integer values (can be empty)
4404 # @ingroup l1_auxiliary
4405 def GetLastCreatedElems(self):
4406 return self.editor.GetLastCreatedElems()
4408 ## Clears sequences of nodes and elements created by mesh edition oparations
4409 # @ingroup l1_auxiliary
4410 def ClearLastCreated(self):
4411 self.editor.ClearLastCreated()
4413 ## Creates Duplicates given elements, i.e. creates new elements based on the
4414 # same nodes as the given ones.
4415 # @param theElements - container of elements to duplicate. It can be a Mesh,
4416 # sub-mesh, group, filter or a list of element IDs.
4417 # @param theGroupName - a name of group to contain the generated elements.
4418 # If a group with such a name already exists, the new elements
4419 # are added to the existng group, else a new group is created.
4420 # If \a theGroupName is empty, new elements are not added
4422 # @return a group where the new elements are added. None if theGroupName == "".
4423 # @ingroup l2_modif_edit
4424 def DoubleElements(self, theElements, theGroupName=""):
4425 unRegister = genObjUnRegister()
4426 if isinstance( theElements, Mesh ):
4427 theElements = theElements.mesh
4428 elif isinstance( theElements, list ):
4429 theElements = self.GetIDSource( theElements, SMESH.ALL )
4430 unRegister.set( theElements )
4431 return self.editor.DoubleElements(theElements, theGroupName)
4433 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4434 # @param theNodes identifiers of nodes to be doubled
4435 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4436 # nodes. If list of element identifiers is empty then nodes are doubled but
4437 # they not assigned to elements
4438 # @return TRUE if operation has been completed successfully, FALSE otherwise
4439 # @ingroup l2_modif_edit
4440 def DoubleNodes(self, theNodes, theModifiedElems):
4441 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4443 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4444 # This method provided for convenience works as DoubleNodes() described above.
4445 # @param theNodeId identifiers of node to be doubled
4446 # @param theModifiedElems identifiers of elements to be updated
4447 # @return TRUE if operation has been completed successfully, FALSE otherwise
4448 # @ingroup l2_modif_edit
4449 def DoubleNode(self, theNodeId, theModifiedElems):
4450 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4452 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4453 # This method provided for convenience works as DoubleNodes() described above.
4454 # @param theNodes group of nodes to be doubled
4455 # @param theModifiedElems group of elements to be updated.
4456 # @param theMakeGroup forces the generation of a group containing new nodes.
4457 # @return TRUE or a created group if operation has been completed successfully,
4458 # FALSE or None otherwise
4459 # @ingroup l2_modif_edit
4460 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4462 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4463 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4465 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4466 # This method provided for convenience works as DoubleNodes() described above.
4467 # @param theNodes list of groups of nodes to be doubled
4468 # @param theModifiedElems list of groups of elements to be updated.
4469 # @param theMakeGroup forces the generation of a group containing new nodes.
4470 # @return TRUE if operation has been completed successfully, FALSE otherwise
4471 # @ingroup l2_modif_edit
4472 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4474 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4475 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4477 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4478 # @param theElems - the list of elements (edges or faces) to be replicated
4479 # The nodes for duplication could be found from these elements
4480 # @param theNodesNot - list of nodes to NOT replicate
4481 # @param theAffectedElems - the list of elements (cells and edges) to which the
4482 # replicated nodes should be associated to.
4483 # @return TRUE if operation has been completed successfully, FALSE otherwise
4484 # @ingroup l2_modif_edit
4485 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4486 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4488 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4489 # @param theElems - the list of elements (edges or faces) to be replicated
4490 # The nodes for duplication could be found from these elements
4491 # @param theNodesNot - list of nodes to NOT replicate
4492 # @param theShape - shape to detect affected elements (element which geometric center
4493 # located on or inside shape).
4494 # The replicated nodes should be associated to affected elements.
4495 # @return TRUE if operation has been completed successfully, FALSE otherwise
4496 # @ingroup l2_modif_edit
4497 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4498 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4500 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4501 # This method provided for convenience works as DoubleNodes() described above.
4502 # @param theElems - group of of elements (edges or faces) to be replicated
4503 # @param theNodesNot - group of nodes not to replicated
4504 # @param theAffectedElems - group of elements to which the replicated nodes
4505 # should be associated to.
4506 # @param theMakeGroup forces the generation of a group containing new elements.
4507 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4508 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4509 # FALSE or None otherwise
4510 # @ingroup l2_modif_edit
4511 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4512 theMakeGroup=False, theMakeNodeGroup=False):
4513 if theMakeGroup or theMakeNodeGroup:
4514 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4516 theMakeGroup, theMakeNodeGroup)
4517 if theMakeGroup and theMakeNodeGroup:
4520 return twoGroups[ int(theMakeNodeGroup) ]
4521 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4523 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4524 # This method provided for convenience works as DoubleNodes() described above.
4525 # @param theElems - group of of elements (edges or faces) to be replicated
4526 # @param theNodesNot - group of nodes not to replicated
4527 # @param theShape - shape to detect affected elements (element which geometric center
4528 # located on or inside shape).
4529 # The replicated nodes should be associated to affected elements.
4530 # @ingroup l2_modif_edit
4531 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4532 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4534 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4535 # This method provided for convenience works as DoubleNodes() described above.
4536 # @param theElems - list of groups of elements (edges or faces) to be replicated
4537 # @param theNodesNot - list of groups of nodes not to replicated
4538 # @param theAffectedElems - group of elements to which the replicated nodes
4539 # should be associated to.
4540 # @param theMakeGroup forces the generation of a group containing new elements.
4541 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4542 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4543 # FALSE or None otherwise
4544 # @ingroup l2_modif_edit
4545 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4546 theMakeGroup=False, theMakeNodeGroup=False):
4547 if theMakeGroup or theMakeNodeGroup:
4548 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4550 theMakeGroup, theMakeNodeGroup)
4551 if theMakeGroup and theMakeNodeGroup:
4554 return twoGroups[ int(theMakeNodeGroup) ]
4555 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4557 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4558 # This method provided for convenience works as DoubleNodes() described above.
4559 # @param theElems - list of groups of elements (edges or faces) to be replicated
4560 # @param theNodesNot - list of groups of nodes not to replicated
4561 # @param theShape - shape to detect affected elements (element which geometric center
4562 # located on or inside shape).
4563 # The replicated nodes should be associated to affected elements.
4564 # @return TRUE if operation has been completed successfully, FALSE otherwise
4565 # @ingroup l2_modif_edit
4566 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4567 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4569 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4570 # This method is the first step of DoubleNodeElemGroupsInRegion.
4571 # @param theElems - list of groups of elements (edges or faces) to be replicated
4572 # @param theNodesNot - list of groups of nodes not to replicated
4573 # @param theShape - shape to detect affected elements (element which geometric center
4574 # located on or inside shape).
4575 # The replicated nodes should be associated to affected elements.
4576 # @return groups of affected elements
4577 # @ingroup l2_modif_edit
4578 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4579 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4581 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4582 # The list of groups must describe a partition of the mesh volumes.
4583 # The nodes of the internal faces at the boundaries of the groups are doubled.
4584 # In option, the internal faces are replaced by flat elements.
4585 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4586 # @param theDomains - list of groups of volumes
4587 # @param createJointElems - if TRUE, create the elements
4588 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4589 # the boundary between \a theDomains and the rest mesh
4590 # @return TRUE if operation has been completed successfully, FALSE otherwise
4591 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4592 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4594 ## Double nodes on some external faces and create flat elements.
4595 # Flat elements are mainly used by some types of mechanic calculations.
4597 # Each group of the list must be constituted of faces.
4598 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4599 # @param theGroupsOfFaces - list of groups of faces
4600 # @return TRUE if operation has been completed successfully, FALSE otherwise
4601 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4602 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4604 ## identify all the elements around a geom shape, get the faces delimiting the hole
4606 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4607 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4609 def _getFunctor(self, funcType ):
4610 fn = self.functors[ funcType._v ]
4612 fn = self.smeshpyD.GetFunctor(funcType)
4613 fn.SetMesh(self.mesh)
4614 self.functors[ funcType._v ] = fn
4617 ## Returns value of a functor for a given element
4618 # @param funcType an item of SMESH.FunctorType enum
4619 # @param elemId element or node ID
4620 # @param isElem @a elemId is ID of element or node
4621 # @return the functor value or zero in case of invalid arguments
4622 def FunctorValue(self, funcType, elemId, isElem=True):
4623 fn = self._getFunctor( funcType )
4624 if fn.GetElementType() == self.GetElementType(elemId, isElem):
4625 val = fn.GetValue(elemId)
4630 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4631 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4632 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4633 # @ingroup l1_measurements
4634 def GetLength(self, elemId=None):
4637 length = self.smeshpyD.GetLength(self)
4639 length = self.FunctorValue(SMESH.FT_Length, elemId)
4642 ## Get area of 2D element or sum of areas of all 2D mesh elements
4643 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4644 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4645 # @ingroup l1_measurements
4646 def GetArea(self, elemId=None):
4649 area = self.smeshpyD.GetArea(self)
4651 area = self.FunctorValue(SMESH.FT_Area, elemId)
4654 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4655 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4656 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4657 # @ingroup l1_measurements
4658 def GetVolume(self, elemId=None):
4661 volume = self.smeshpyD.GetVolume(self)
4663 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4666 ## Get maximum element length.
4667 # @param elemId mesh element ID
4668 # @return element's maximum length value
4669 # @ingroup l1_measurements
4670 def GetMaxElementLength(self, elemId):
4671 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4672 ftype = SMESH.FT_MaxElementLength3D
4674 ftype = SMESH.FT_MaxElementLength2D
4675 return self.FunctorValue(ftype, elemId)
4677 ## Get aspect ratio of 2D or 3D element.
4678 # @param elemId mesh element ID
4679 # @return element's aspect ratio value
4680 # @ingroup l1_measurements
4681 def GetAspectRatio(self, elemId):
4682 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4683 ftype = SMESH.FT_AspectRatio3D
4685 ftype = SMESH.FT_AspectRatio
4686 return self.FunctorValue(ftype, elemId)
4688 ## Get warping angle of 2D element.
4689 # @param elemId mesh element ID
4690 # @return element's warping angle value
4691 # @ingroup l1_measurements
4692 def GetWarping(self, elemId):
4693 return self.FunctorValue(SMESH.FT_Warping, elemId)
4695 ## Get minimum angle of 2D element.
4696 # @param elemId mesh element ID
4697 # @return element's minimum angle value
4698 # @ingroup l1_measurements
4699 def GetMinimumAngle(self, elemId):
4700 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4702 ## Get taper of 2D element.
4703 # @param elemId mesh element ID
4704 # @return element's taper value
4705 # @ingroup l1_measurements
4706 def GetTaper(self, elemId):
4707 return self.FunctorValue(SMESH.FT_Taper, elemId)
4709 ## Get skew of 2D element.
4710 # @param elemId mesh element ID
4711 # @return element's skew value
4712 # @ingroup l1_measurements
4713 def GetSkew(self, elemId):
4714 return self.FunctorValue(SMESH.FT_Skew, elemId)
4716 ## Return minimal and maximal value of a given functor.
4717 # @param funType a functor type, an item of SMESH.FunctorType enum
4718 # (one of SMESH.FunctorType._items)
4719 # @param meshPart a part of mesh (group, sub-mesh) to treat
4720 # @return tuple (min,max)
4721 # @ingroup l1_measurements
4722 def GetMinMax(self, funType, meshPart=None):
4723 unRegister = genObjUnRegister()
4724 if isinstance( meshPart, list ):
4725 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4726 unRegister.set( meshPart )
4727 if isinstance( meshPart, Mesh ):
4728 meshPart = meshPart.mesh
4729 fun = self._getFunctor( funType )
4732 hist = fun.GetLocalHistogram( 1, False, meshPart )
4734 hist = fun.GetHistogram( 1, False )
4736 return hist[0].min, hist[0].max
4739 pass # end of Mesh class
4741 ## class used to add to SMESH_MeshEditor methods removed from its CORBA API
4743 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4745 SMESH._objref_SMESH_MeshEditor.__init__(self)
4747 def __getattr__(self, name ): # method called if an attribute not found
4748 if not self.mesh: # look for name() method in Mesh class
4749 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
4750 if hasattr( self.mesh, name ):
4751 return getattr( self.mesh, name )
4752 if name == "ExtrusionAlongPathObjX":
4753 return getattr( self.mesh, "ExtrusionAlongPathX" )
4754 print name, "NOT FOUND"
4757 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
4759 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4761 class Pattern(SMESH._objref_SMESH_Pattern):
4763 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4764 decrFun = lambda i: i-1
4765 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4766 theMesh.SetParameters(Parameters)
4767 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4769 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4770 decrFun = lambda i: i-1
4771 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4772 theMesh.SetParameters(Parameters)
4773 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4775 # Registering the new proxy for Pattern
4776 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4778 ## Private class used to bind methods creating algorithms to the class Mesh
4783 self.defaultAlgoType = ""
4784 self.algoTypeToClass = {}
4786 # Stores a python class of algorithm
4787 def add(self, algoClass):
4788 if type( algoClass ).__name__ == 'classobj' and \
4789 hasattr( algoClass, "algoType"):
4790 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4791 if not self.defaultAlgoType and \
4792 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4793 self.defaultAlgoType = algoClass.algoType
4794 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4796 # creates a copy of self and assign mesh to the copy
4797 def copy(self, mesh):
4798 other = algoCreator()
4799 other.defaultAlgoType = self.defaultAlgoType
4800 other.algoTypeToClass = self.algoTypeToClass
4804 # creates an instance of algorithm
4805 def __call__(self,algo="",geom=0,*args):
4806 algoType = self.defaultAlgoType
4807 for arg in args + (algo,geom):
4808 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4810 if isinstance( arg, str ) and arg:
4812 if not algoType and self.algoTypeToClass:
4813 algoType = self.algoTypeToClass.keys()[0]
4814 if self.algoTypeToClass.has_key( algoType ):
4815 #print "Create algo",algoType
4816 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4817 raise RuntimeError, "No class found for algo type %s" % algoType
4820 # Private class used to substitute and store variable parameters of hypotheses.
4822 class hypMethodWrapper:
4823 def __init__(self, hyp, method):
4825 self.method = method
4826 #print "REBIND:", method.__name__
4829 # call a method of hypothesis with calling SetVarParameter() before
4830 def __call__(self,*args):
4832 return self.method( self.hyp, *args ) # hypothesis method with no args
4834 #print "MethWrapper.__call__",self.method.__name__, args
4836 parsed = ParseParameters(*args) # replace variables with their values
4837 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4838 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4839 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4840 # maybe there is a replaced string arg which is not variable
4841 result = self.method( self.hyp, *args )
4842 except ValueError, detail: # raised by ParseParameters()
4844 result = self.method( self.hyp, *args )
4845 except omniORB.CORBA.BAD_PARAM:
4846 raise ValueError, detail # wrong variable name
4851 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4852 class genObjUnRegister:
4854 def __init__(self, genObj=None):
4855 self.genObjList = []
4859 def set(self, genObj):
4860 "Store one or a list of of SALOME.GenericObj'es"
4861 if isinstance( genObj, list ):
4862 self.genObjList.extend( genObj )
4864 self.genObjList.append( genObj )
4868 for genObj in self.genObjList:
4869 if genObj and hasattr( genObj, "UnRegister" ):
4872 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4874 #print "pluginName: ", pluginName
4875 pluginBuilderName = pluginName + "Builder"
4877 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4878 except Exception, e:
4879 from salome_utils import verbose
4880 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4882 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4883 plugin = eval( pluginBuilderName )
4884 #print " plugin:" , str(plugin)
4886 # add methods creating algorithms to Mesh
4887 for k in dir( plugin ):
4888 if k[0] == '_': continue
4889 algo = getattr( plugin, k )
4890 #print " algo:", str(algo)
4891 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4892 #print " meshMethod:" , str(algo.meshMethod)
4893 if not hasattr( Mesh, algo.meshMethod ):
4894 setattr( Mesh, algo.meshMethod, algoCreator() )
4896 getattr( Mesh, algo.meshMethod ).add( algo )