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):
164 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
166 SMESH.AxisStruct.__init__ = __initAxisStruct
168 smeshPrecisionConfusion = 1.e-07
169 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
170 if abs(val1 - val2) < tol:
180 if isinstance(obj, SALOMEDS._objref_SObject):
184 ior = salome.orb.object_to_string(obj)
189 studies = salome.myStudyManager.GetOpenStudies()
190 for sname in studies:
191 s = salome.myStudyManager.GetStudyByName(sname)
193 sobj = s.FindObjectIOR(ior)
194 if not sobj: continue
195 return sobj.GetName()
196 if hasattr(obj, "GetName"):
197 # unknown CORBA object, having GetName() method
200 # unknown CORBA object, no GetName() method
203 if hasattr(obj, "GetName"):
204 # unknown non-CORBA object, having GetName() method
207 raise RuntimeError, "Null or invalid object"
209 ## Prints error message if a hypothesis was not assigned.
210 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
212 hypType = "algorithm"
214 hypType = "hypothesis"
217 if hasattr( status, "__getitem__" ):
218 status,reason = status[0],status[1]
219 if status == HYP_UNKNOWN_FATAL :
220 reason = "for unknown reason"
221 elif status == HYP_INCOMPATIBLE :
222 reason = "this hypothesis mismatches the algorithm"
223 elif status == HYP_NOTCONFORM :
224 reason = "a non-conform mesh would be built"
225 elif status == HYP_ALREADY_EXIST :
226 if isAlgo: return # it does not influence anything
227 reason = hypType + " of the same dimension is already assigned to this shape"
228 elif status == HYP_BAD_DIM :
229 reason = hypType + " mismatches the shape"
230 elif status == HYP_CONCURENT :
231 reason = "there are concurrent hypotheses on sub-shapes"
232 elif status == HYP_BAD_SUBSHAPE :
233 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
234 elif status == HYP_BAD_GEOMETRY:
235 reason = "geometry mismatches the expectation of the algorithm"
236 elif status == HYP_HIDDEN_ALGO:
237 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
238 elif status == HYP_HIDING_ALGO:
239 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
240 elif status == HYP_NEED_SHAPE:
241 reason = "algorithm can't work without shape"
242 elif status == HYP_INCOMPAT_HYPS:
248 where = '"%s"' % geomName
250 meshName = GetName( mesh )
251 if meshName and meshName != NO_NAME:
252 where = '"%s" in "%s"' % ( geomName, meshName )
253 if status < HYP_UNKNOWN_FATAL and where:
254 print '"%s" was assigned to %s but %s' %( hypName, where, reason )
256 print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
258 print '"%s" was not assigned : %s' %( hypName, reason )
261 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
262 def AssureGeomPublished(mesh, geom, name=''):
263 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
265 if not geom.GetStudyEntry() and \
266 mesh.smeshpyD.GetCurrentStudy():
268 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
269 if studyID != mesh.geompyD.myStudyId:
270 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
272 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
273 # for all groups SubShapeName() returns "Compound_-1"
274 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
276 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
278 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
281 ## Return the first vertex of a geometrical edge by ignoring orientation
282 def FirstVertexOnCurve(mesh, edge):
283 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
285 raise TypeError, "Given object has no vertices"
286 if len( vv ) == 1: return vv[0]
287 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
288 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
289 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
290 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
293 dist1 += abs( xyz[i] - xyz1[i] )
294 dist2 += abs( xyz[i] - xyz2[i] )
300 # end of l1_auxiliary
304 # Warning: smeshInst is a singleton
310 ## This class allows to create, load or manipulate meshes
311 # It has a set of methods to create load or copy meshes, to combine several meshes.
312 # It also has methods to get infos on meshes.
313 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
315 # MirrorType enumeration
316 POINT = SMESH_MeshEditor.POINT
317 AXIS = SMESH_MeshEditor.AXIS
318 PLANE = SMESH_MeshEditor.PLANE
320 # Smooth_Method enumeration
321 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
322 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
324 PrecisionConfusion = smeshPrecisionConfusion
326 # TopAbs_State enumeration
327 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
329 # Methods of splitting a hexahedron into tetrahedra
330 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
336 #print "==== __new__", engine, smeshInst, doLcc
338 if smeshInst is None:
339 # smesh engine is either retrieved from engine, or created
341 # Following test avoids a recursive loop
343 if smeshInst is not None:
344 # smesh engine not created: existing engine found
348 # FindOrLoadComponent called:
349 # 1. CORBA resolution of server
350 # 2. the __new__ method is called again
351 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
352 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
354 # FindOrLoadComponent not called
355 if smeshInst is None:
356 # smeshBuilder instance is created from lcc.FindOrLoadComponent
357 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
358 smeshInst = super(smeshBuilder,cls).__new__(cls)
360 # smesh engine not created: existing engine found
361 #print "==== existing ", engine, smeshInst, doLcc
363 #print "====1 ", smeshInst
366 #print "====2 ", smeshInst
371 #print "--------------- smeshbuilder __init__ ---", created
374 SMESH._objref_SMESH_Gen.__init__(self)
376 ## Dump component to the Python script
377 # This method overrides IDL function to allow default values for the parameters.
378 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
379 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
381 ## Set mode of DumpPython(), \a historical or \a snapshot.
382 # In the \a historical mode, the Python Dump script includes all commands
383 # performed by SMESH engine. In the \a snapshot mode, commands
384 # relating to objects removed from the Study are excluded from the script
385 # as well as commands not influencing the current state of meshes
386 def SetDumpPythonHistorical(self, isHistorical):
387 if isHistorical: val = "true"
389 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
391 ## Sets the current study and Geometry component
392 # @ingroup l1_auxiliary
393 def init_smesh(self,theStudy,geompyD = None):
395 self.SetCurrentStudy(theStudy,geompyD)
398 notebook.myStudy = theStudy
400 ## Creates a mesh. This can be either an empty mesh, possibly having an underlying geometry,
401 # or a mesh wrapping a CORBA mesh given as a parameter.
402 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
403 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
404 # (2) a Geometrical object for meshing or
406 # @param name the name for the new mesh.
407 # @return an instance of Mesh class.
408 # @ingroup l2_construct
409 def Mesh(self, obj=0, name=0):
410 if isinstance(obj,str):
412 return Mesh(self,self.geompyD,obj,name)
414 ## Returns a long value from enumeration
415 # @ingroup l1_controls
416 def EnumToLong(self,theItem):
419 ## Returns a string representation of the color.
420 # To be used with filters.
421 # @param c color value (SALOMEDS.Color)
422 # @ingroup l1_controls
423 def ColorToString(self,c):
425 if isinstance(c, SALOMEDS.Color):
426 val = "%s;%s;%s" % (c.R, c.G, c.B)
427 elif isinstance(c, str):
430 raise ValueError, "Color value should be of string or SALOMEDS.Color type"
433 ## Gets PointStruct from vertex
434 # @param theVertex a GEOM object(vertex)
435 # @return SMESH.PointStruct
436 # @ingroup l1_auxiliary
437 def GetPointStruct(self,theVertex):
438 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
439 return PointStruct(x,y,z)
441 ## Gets DirStruct from vector
442 # @param theVector a GEOM object(vector)
443 # @return SMESH.DirStruct
444 # @ingroup l1_auxiliary
445 def GetDirStruct(self,theVector):
446 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447 if(len(vertices) != 2):
448 print "Error: vector object is incorrect."
450 p1 = self.geompyD.PointCoordinates(vertices[0])
451 p2 = self.geompyD.PointCoordinates(vertices[1])
452 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
453 dirst = DirStruct(pnt)
456 ## Makes DirStruct from a triplet
457 # @param x,y,z vector components
458 # @return SMESH.DirStruct
459 # @ingroup l1_auxiliary
460 def MakeDirStruct(self,x,y,z):
461 pnt = PointStruct(x,y,z)
462 return DirStruct(pnt)
464 ## Get AxisStruct from object
465 # @param theObj a GEOM object (line or plane)
466 # @return SMESH.AxisStruct
467 # @ingroup l1_auxiliary
468 def GetAxisStruct(self,theObj):
470 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
473 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
474 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
475 vertex1 = self.geompyD.PointCoordinates(vertex1)
476 vertex2 = self.geompyD.PointCoordinates(vertex2)
477 vertex3 = self.geompyD.PointCoordinates(vertex3)
478 vertex4 = self.geompyD.PointCoordinates(vertex4)
479 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
480 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
481 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] ]
482 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
483 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
484 elif len(edges) == 1:
485 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
486 p1 = self.geompyD.PointCoordinates( vertex1 )
487 p2 = self.geompyD.PointCoordinates( vertex2 )
488 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
489 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
490 elif theObj.GetShapeType() == GEOM.VERTEX:
491 x,y,z = self.geompyD.PointCoordinates( theObj )
492 axis = AxisStruct( x,y,z, 1,0,0,)
493 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
496 # From SMESH_Gen interface:
497 # ------------------------
499 ## Sets the given name to the object
500 # @param obj the object to rename
501 # @param name a new object name
502 # @ingroup l1_auxiliary
503 def SetName(self, obj, name):
504 if isinstance( obj, Mesh ):
506 elif isinstance( obj, Mesh_Algorithm ):
507 obj = obj.GetAlgorithm()
508 ior = salome.orb.object_to_string(obj)
509 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
511 ## Sets the current mode
512 # @ingroup l1_auxiliary
513 def SetEmbeddedMode( self,theMode ):
514 #self.SetEmbeddedMode(theMode)
515 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
517 ## Gets the current mode
518 # @ingroup l1_auxiliary
519 def IsEmbeddedMode(self):
520 #return self.IsEmbeddedMode()
521 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
523 ## Sets the current study. Calling SetCurrentStudy( None ) allows to
524 # switch OFF automatic pubilishing in the Study of mesh objects.
525 # @ingroup l1_auxiliary
526 def SetCurrentStudy( self, theStudy, geompyD = None ):
527 #self.SetCurrentStudy(theStudy)
529 from salome.geom import geomBuilder
530 geompyD = geomBuilder.geom
533 self.SetGeomEngine(geompyD)
534 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
537 notebook = salome_notebook.NoteBook( theStudy )
539 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
541 sb = theStudy.NewBuilder()
542 sc = theStudy.FindComponent("SMESH")
543 if sc: sb.LoadWith(sc, self)
547 ## Gets the current study
548 # @ingroup l1_auxiliary
549 def GetCurrentStudy(self):
550 #return self.GetCurrentStudy()
551 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
553 ## Creates a Mesh object importing data from the given UNV file
554 # @return an instance of Mesh class
556 def CreateMeshesFromUNV( self,theFileName ):
557 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
558 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
561 ## Creates a Mesh object(s) importing data from the given MED file
562 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
564 def CreateMeshesFromMED( self,theFileName ):
565 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
566 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
567 return aMeshes, aStatus
569 ## Creates a Mesh object(s) importing data from the given SAUV file
570 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
572 def CreateMeshesFromSAUV( self,theFileName ):
573 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
574 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
575 return aMeshes, aStatus
577 ## Creates a Mesh object importing data from the given STL file
578 # @return an instance of Mesh class
580 def CreateMeshesFromSTL( self, theFileName ):
581 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
582 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
585 ## Creates Mesh objects importing data from the given CGNS file
586 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
588 def CreateMeshesFromCGNS( self, theFileName ):
589 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
590 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
591 return aMeshes, aStatus
593 ## Creates a Mesh object importing data from the given GMF file.
594 # GMF files must have .mesh extension for the ASCII format and .meshb for
596 # @return [ an instance of Mesh class, SMESH.ComputeError ]
598 def CreateMeshesFromGMF( self, theFileName ):
599 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
602 if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
603 return Mesh(self, self.geompyD, aSmeshMesh), error
605 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
606 # present in the new mesh.
607 # @param meshes the meshes to combine into one mesh
608 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
609 # @param mergeNodesAndElements if true, equal nodes and elements are merged
610 # @param mergeTolerance tolerance for merging nodes
611 # @param allGroups forces creation of groups corresponding to every input mesh
612 # @param name name of a new mesh
613 # @return an instance of Mesh class
614 def Concatenate( self, meshes, uniteIdenticalGroups,
615 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
617 if not meshes: return None
618 for i,m in enumerate(meshes):
619 if isinstance(m, Mesh):
620 meshes[i] = m.GetMesh()
621 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
622 meshes[0].SetParameters(Parameters)
624 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
625 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
627 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
628 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
629 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
632 ## Create a mesh by copying a part of another mesh.
633 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
634 # to copy nodes or elements not contained in any mesh object,
635 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
636 # @param meshName a name of the new mesh
637 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
638 # @param toKeepIDs to preserve order of the copied elements or not
639 # @return an instance of Mesh class
640 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
641 if (isinstance( meshPart, Mesh )):
642 meshPart = meshPart.GetMesh()
643 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
644 return Mesh(self, self.geompyD, mesh)
646 ## From SMESH_Gen interface
647 # @return the list of integer values
648 # @ingroup l1_auxiliary
649 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
650 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
652 ## From SMESH_Gen interface. Creates a pattern
653 # @return an instance of SMESH_Pattern
655 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
656 # @ingroup l2_modif_patterns
657 def GetPattern(self):
658 return SMESH._objref_SMESH_Gen.GetPattern(self)
660 ## Sets number of segments per diagonal of boundary box of geometry by which
661 # default segment length of appropriate 1D hypotheses is defined.
662 # Default value is 10
663 # @ingroup l1_auxiliary
664 def SetBoundaryBoxSegmentation(self, nbSegments):
665 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
667 # Filtering. Auxiliary functions:
668 # ------------------------------
670 ## Creates an empty criterion
671 # @return SMESH.Filter.Criterion
672 # @ingroup l1_controls
673 def GetEmptyCriterion(self):
674 Type = self.EnumToLong(FT_Undefined)
675 Compare = self.EnumToLong(FT_Undefined)
679 UnaryOp = self.EnumToLong(FT_Undefined)
680 BinaryOp = self.EnumToLong(FT_Undefined)
683 Precision = -1 ##@1e-07
684 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
685 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
687 ## Creates a criterion by the given parameters
688 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
689 # @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
690 # @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
691 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
692 # @param Threshold the threshold value (range of ids as string, shape, numeric)
693 # @param UnaryOp FT_LogicalNOT or FT_Undefined
694 # @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
695 # FT_Undefined (must be for the last criterion of all criteria)
696 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
697 # FT_LyingOnGeom, FT_CoplanarFaces criteria
698 # @return SMESH.Filter.Criterion
700 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
701 # @ingroup l1_controls
702 def GetCriterion(self,elementType,
704 Compare = FT_EqualTo,
706 UnaryOp=FT_Undefined,
707 BinaryOp=FT_Undefined,
709 if not CritType in SMESH.FunctorType._items:
710 raise TypeError, "CritType should be of SMESH.FunctorType"
711 aCriterion = self.GetEmptyCriterion()
712 aCriterion.TypeOfElement = elementType
713 aCriterion.Type = self.EnumToLong(CritType)
714 aCriterion.Tolerance = Tolerance
716 aThreshold = Threshold
718 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
719 aCriterion.Compare = self.EnumToLong(Compare)
720 elif Compare == "=" or Compare == "==":
721 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
723 aCriterion.Compare = self.EnumToLong(FT_LessThan)
725 aCriterion.Compare = self.EnumToLong(FT_MoreThan)
726 elif Compare != FT_Undefined:
727 aCriterion.Compare = self.EnumToLong(FT_EqualTo)
730 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
731 FT_BelongToCylinder, FT_LyingOnGeom]:
732 # Checks that Threshold is GEOM object
733 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
734 aCriterion.ThresholdStr = GetName(aThreshold)
735 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
736 if not aCriterion.ThresholdID:
737 name = aCriterion.ThresholdStr
739 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
740 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
741 #raise RuntimeError, "Threshold shape must be published"
743 print "Error: The Threshold should be a shape."
745 if isinstance(UnaryOp,float):
746 aCriterion.Tolerance = UnaryOp
747 UnaryOp = FT_Undefined
749 elif CritType == FT_RangeOfIds:
750 # Checks that Threshold is string
751 if isinstance(aThreshold, str):
752 aCriterion.ThresholdStr = aThreshold
754 print "Error: The Threshold should be a string."
756 elif CritType == FT_CoplanarFaces:
757 # Checks the Threshold
758 if isinstance(aThreshold, int):
759 aCriterion.ThresholdID = str(aThreshold)
760 elif isinstance(aThreshold, str):
763 raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
764 aCriterion.ThresholdID = aThreshold
767 "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
768 elif CritType == FT_ConnectedElements:
769 # Checks the Threshold
770 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
771 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
772 if not aCriterion.ThresholdID:
773 name = aThreshold.GetName()
775 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
776 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
777 elif isinstance(aThreshold, int): # node id
778 aCriterion.Threshold = aThreshold
779 elif isinstance(aThreshold, list): # 3 point coordinates
780 if len( aThreshold ) < 3:
781 raise ValueError, "too few point coordinates, must be 3"
782 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
783 elif isinstance(aThreshold, str):
784 if aThreshold.isdigit():
785 aCriterion.Threshold = aThreshold # node id
787 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
790 "The Threshold should either a VERTEX, or a node ID, "\
791 "or a list of point coordinates and not '%s'"%aThreshold
792 elif CritType == FT_ElemGeomType:
793 # Checks the Threshold
795 aCriterion.Threshold = self.EnumToLong(aThreshold)
796 assert( aThreshold in SMESH.GeometryType._items )
798 if isinstance(aThreshold, int):
799 aCriterion.Threshold = aThreshold
801 print "Error: The Threshold should be an integer or SMESH.GeometryType."
805 elif CritType == FT_EntityType:
806 # Checks the Threshold
808 aCriterion.Threshold = self.EnumToLong(aThreshold)
809 assert( aThreshold in SMESH.EntityType._items )
811 if isinstance(aThreshold, int):
812 aCriterion.Threshold = aThreshold
814 print "Error: The Threshold should be an integer or SMESH.EntityType."
819 elif CritType == FT_GroupColor:
820 # Checks the Threshold
822 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
824 print "Error: The threshold value should be of SALOMEDS.Color type"
827 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
828 FT_LinearOrQuadratic, FT_BadOrientedVolume,
829 FT_BareBorderFace, FT_BareBorderVolume,
830 FT_OverConstrainedFace, FT_OverConstrainedVolume,
831 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
832 # At this point the Threshold is unnecessary
833 if aThreshold == FT_LogicalNOT:
834 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
835 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
836 aCriterion.BinaryOp = aThreshold
840 aThreshold = float(aThreshold)
841 aCriterion.Threshold = aThreshold
843 print "Error: The Threshold should be a number."
846 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
847 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
849 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
850 aCriterion.BinaryOp = self.EnumToLong(Threshold)
852 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
853 aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
855 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
856 aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
860 ## Creates a filter with the given parameters
861 # @param elementType the type of elements in the group
862 # @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
863 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
864 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
865 # @param UnaryOp FT_LogicalNOT or FT_Undefined
866 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
867 # FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
868 # @param mesh the mesh to initialize the filter with
869 # @return SMESH_Filter
871 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
872 # @ingroup l1_controls
873 def GetFilter(self,elementType,
874 CritType=FT_Undefined,
877 UnaryOp=FT_Undefined,
880 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
881 aFilterMgr = self.CreateFilterManager()
882 aFilter = aFilterMgr.CreateFilter()
884 aCriteria.append(aCriterion)
885 aFilter.SetCriteria(aCriteria)
887 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
888 else : aFilter.SetMesh( mesh )
889 aFilterMgr.UnRegister()
892 ## Creates a filter from criteria
893 # @param criteria a list of criteria
894 # @param binOp binary operator used when binary operator of criteria is undefined
895 # @return SMESH_Filter
897 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
898 # @ingroup l1_controls
899 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
900 for i in range( len( criteria ) - 1 ):
901 if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
902 criteria[i].BinaryOp = self.EnumToLong( binOp )
903 aFilterMgr = self.CreateFilterManager()
904 aFilter = aFilterMgr.CreateFilter()
905 aFilter.SetCriteria(criteria)
906 aFilterMgr.UnRegister()
909 ## Creates a numerical functor by its type
910 # @param theCriterion FT_...; functor type
911 # @return SMESH_NumericalFunctor
912 # @ingroup l1_controls
913 def GetFunctor(self,theCriterion):
914 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
916 aFilterMgr = self.CreateFilterManager()
918 if theCriterion == FT_AspectRatio:
919 functor = aFilterMgr.CreateAspectRatio()
920 elif theCriterion == FT_AspectRatio3D:
921 functor = aFilterMgr.CreateAspectRatio3D()
922 elif theCriterion == FT_Warping:
923 functor = aFilterMgr.CreateWarping()
924 elif theCriterion == FT_MinimumAngle:
925 functor = aFilterMgr.CreateMinimumAngle()
926 elif theCriterion == FT_Taper:
927 functor = aFilterMgr.CreateTaper()
928 elif theCriterion == FT_Skew:
929 functor = aFilterMgr.CreateSkew()
930 elif theCriterion == FT_Area:
931 functor = aFilterMgr.CreateArea()
932 elif theCriterion == FT_Volume3D:
933 functor = aFilterMgr.CreateVolume3D()
934 elif theCriterion == FT_MaxElementLength2D:
935 functor = aFilterMgr.CreateMaxElementLength2D()
936 elif theCriterion == FT_MaxElementLength3D:
937 functor = aFilterMgr.CreateMaxElementLength3D()
938 elif theCriterion == FT_MultiConnection:
939 functor = aFilterMgr.CreateMultiConnection()
940 elif theCriterion == FT_MultiConnection2D:
941 functor = aFilterMgr.CreateMultiConnection2D()
942 elif theCriterion == FT_Length:
943 functor = aFilterMgr.CreateLength()
944 elif theCriterion == FT_Length2D:
945 functor = aFilterMgr.CreateLength2D()
947 print "Error: given parameter is not numerical functor type."
948 aFilterMgr.UnRegister()
951 ## Creates hypothesis
952 # @param theHType mesh hypothesis type (string)
953 # @param theLibName mesh plug-in library name
954 # @return created hypothesis instance
955 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
956 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
958 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
961 # wrap hypothesis methods
962 #print "HYPOTHESIS", theHType
963 for meth_name in dir( hyp.__class__ ):
964 if not meth_name.startswith("Get") and \
965 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
966 method = getattr ( hyp.__class__, meth_name )
968 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
972 ## Gets the mesh statistic
973 # @return dictionary "element type" - "count of elements"
974 # @ingroup l1_meshinfo
975 def GetMeshInfo(self, obj):
976 if isinstance( obj, Mesh ):
979 if hasattr(obj, "GetMeshInfo"):
980 values = obj.GetMeshInfo()
981 for i in range(SMESH.Entity_Last._v):
982 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
986 ## Get minimum distance between two objects
988 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
989 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
991 # @param src1 first source object
992 # @param src2 second source object
993 # @param id1 node/element id from the first source
994 # @param id2 node/element id from the second (or first) source
995 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
996 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
997 # @return minimum distance value
998 # @sa GetMinDistance()
999 # @ingroup l1_measurements
1000 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1001 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1005 result = result.value
1008 ## Get measure structure specifying minimum distance data between two objects
1010 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1011 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1013 # @param src1 first source object
1014 # @param src2 second source object
1015 # @param id1 node/element id from the first source
1016 # @param id2 node/element id from the second (or first) source
1017 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1018 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1019 # @return Measure structure or None if input data is invalid
1021 # @ingroup l1_measurements
1022 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1023 if isinstance(src1, Mesh): src1 = src1.mesh
1024 if isinstance(src2, Mesh): src2 = src2.mesh
1025 if src2 is None and id2 != 0: src2 = src1
1026 if not hasattr(src1, "_narrow"): return None
1027 src1 = src1._narrow(SMESH.SMESH_IDSource)
1028 if not src1: return None
1029 unRegister = genObjUnRegister()
1032 e = m.GetMeshEditor()
1034 src1 = e.MakeIDSource([id1], SMESH.FACE)
1036 src1 = e.MakeIDSource([id1], SMESH.NODE)
1037 unRegister.set( src1 )
1039 if hasattr(src2, "_narrow"):
1040 src2 = src2._narrow(SMESH.SMESH_IDSource)
1041 if src2 and id2 != 0:
1043 e = m.GetMeshEditor()
1045 src2 = e.MakeIDSource([id2], SMESH.FACE)
1047 src2 = e.MakeIDSource([id2], SMESH.NODE)
1048 unRegister.set( src2 )
1051 aMeasurements = self.CreateMeasurements()
1052 unRegister.set( aMeasurements )
1053 result = aMeasurements.MinDistance(src1, src2)
1056 ## Get bounding box of the specified object(s)
1057 # @param objects single source object or list of source objects
1058 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1059 # @sa GetBoundingBox()
1060 # @ingroup l1_measurements
1061 def BoundingBox(self, objects):
1062 result = self.GetBoundingBox(objects)
1066 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1069 ## Get measure structure specifying bounding box data of the specified object(s)
1070 # @param objects single source object or list of source objects
1071 # @return Measure structure
1073 # @ingroup l1_measurements
1074 def GetBoundingBox(self, objects):
1075 if isinstance(objects, tuple):
1076 objects = list(objects)
1077 if not isinstance(objects, list):
1081 if isinstance(o, Mesh):
1082 srclist.append(o.mesh)
1083 elif hasattr(o, "_narrow"):
1084 src = o._narrow(SMESH.SMESH_IDSource)
1085 if src: srclist.append(src)
1088 aMeasurements = self.CreateMeasurements()
1089 result = aMeasurements.BoundingBox(srclist)
1090 aMeasurements.UnRegister()
1093 ## Get sum of lengths of all 1D elements in the mesh object.
1094 # @param obj mesh, submesh or group
1095 # @return sum of lengths of all 1D elements
1096 # @ingroup l1_measurements
1097 def GetLength(self, obj):
1098 if isinstance(obj, Mesh): obj = obj.mesh
1099 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1100 aMeasurements = self.CreateMeasurements()
1101 value = aMeasurements.Length(obj)
1102 aMeasurements.UnRegister()
1105 ## Get sum of areas of all 2D elements in the mesh object.
1106 # @param obj mesh, submesh or group
1107 # @return sum of areas of all 2D elements
1108 # @ingroup l1_measurements
1109 def GetArea(self, obj):
1110 if isinstance(obj, Mesh): obj = obj.mesh
1111 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1112 aMeasurements = self.CreateMeasurements()
1113 value = aMeasurements.Area(obj)
1114 aMeasurements.UnRegister()
1117 ## Get sum of volumes of all 3D elements in the mesh object.
1118 # @param obj mesh, submesh or group
1119 # @return sum of volumes of all 3D elements
1120 # @ingroup l1_measurements
1121 def GetVolume(self, obj):
1122 if isinstance(obj, Mesh): obj = obj.mesh
1123 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1124 aMeasurements = self.CreateMeasurements()
1125 value = aMeasurements.Volume(obj)
1126 aMeasurements.UnRegister()
1129 pass # end of class smeshBuilder
1132 #Registering the new proxy for SMESH_Gen
1133 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1135 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1136 # interface to create or load meshes.
1141 # salome.salome_init()
1142 # from salome.smesh import smeshBuilder
1143 # smesh = smeshBuilder.New(theStudy)
1145 # @param study SALOME study, generally obtained by salome.myStudy.
1146 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1147 # @return smeshBuilder instance
1149 def New( study, instance=None):
1151 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1152 interface to create or load meshes.
1156 salome.salome_init()
1157 from salome.smesh import smeshBuilder
1158 smesh = smeshBuilder.New(theStudy)
1161 study SALOME study, generally obtained by salome.myStudy.
1162 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1164 smeshBuilder instance
1172 smeshInst = smeshBuilder()
1173 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1174 smeshInst.init_smesh(study)
1178 # Public class: Mesh
1179 # ==================
1181 ## This class allows defining and managing a mesh.
1182 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1183 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1184 # new nodes and elements and by changing the existing entities), to get information
1185 # about a mesh and to export a mesh into different formats.
1187 __metaclass__ = MeshMeta
1195 # Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1196 # sets the GUI name of this mesh to \a name.
1197 # @param smeshpyD an instance of smeshBuilder class
1198 # @param geompyD an instance of geomBuilder class
1199 # @param obj Shape to be meshed or SMESH_Mesh object
1200 # @param name Study name of the mesh
1201 # @ingroup l2_construct
1202 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1203 self.smeshpyD=smeshpyD
1204 self.geompyD=geompyD
1209 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1212 # publish geom of mesh (issue 0021122)
1213 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1215 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1216 if studyID != geompyD.myStudyId:
1217 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1220 geo_name = name + " shape"
1222 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1223 geompyD.addToStudy( self.geom, geo_name )
1224 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1226 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1229 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1231 self.smeshpyD.SetName(self.mesh, name)
1233 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1236 self.geom = self.mesh.GetShapeToMesh()
1238 self.editor = self.mesh.GetMeshEditor()
1239 self.functors = [None] * SMESH.FT_Undefined._v
1241 # set self to algoCreator's
1242 for attrName in dir(self):
1243 attr = getattr( self, attrName )
1244 if isinstance( attr, algoCreator ):
1245 #print "algoCreator ", attrName
1246 setattr( self, attrName, attr.copy( self ))
1251 ## Destructor. Clean-up resources
1254 #self.mesh.UnRegister()
1258 ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1259 # @param theMesh a SMESH_Mesh object
1260 # @ingroup l2_construct
1261 def SetMesh(self, theMesh):
1262 # do not call Register() as this prevents mesh servant deletion at closing study
1263 #if self.mesh: self.mesh.UnRegister()
1266 #self.mesh.Register()
1267 self.geom = self.mesh.GetShapeToMesh()
1270 ## Returns the mesh, that is an instance of SMESH_Mesh interface
1271 # @return a SMESH_Mesh object
1272 # @ingroup l2_construct
1276 ## Gets the name of the mesh
1277 # @return the name of the mesh as a string
1278 # @ingroup l2_construct
1280 name = GetName(self.GetMesh())
1283 ## Sets a name to the mesh
1284 # @param name a new name of the mesh
1285 # @ingroup l2_construct
1286 def SetName(self, name):
1287 self.smeshpyD.SetName(self.GetMesh(), name)
1289 ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1290 # The subMesh object gives access to the IDs of nodes and elements.
1291 # @param geom a geometrical object (shape)
1292 # @param name a name for the submesh
1293 # @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1294 # @ingroup l2_submeshes
1295 def GetSubMesh(self, geom, name):
1296 AssureGeomPublished( self, geom, name )
1297 submesh = self.mesh.GetSubMesh( geom, name )
1300 ## Returns the shape associated to the mesh
1301 # @return a GEOM_Object
1302 # @ingroup l2_construct
1306 ## Associates the given shape to the mesh (entails the recreation of the mesh)
1307 # @param geom the shape to be meshed (GEOM_Object)
1308 # @ingroup l2_construct
1309 def SetShape(self, geom):
1310 self.mesh = self.smeshpyD.CreateMesh(geom)
1312 ## Loads mesh from the study after opening the study
1316 ## Returns true if the hypotheses are defined well
1317 # @param theSubObject a sub-shape of a mesh shape
1318 # @return True or False
1319 # @ingroup l2_construct
1320 def IsReadyToCompute(self, theSubObject):
1321 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1323 ## Returns errors of hypotheses definition.
1324 # The list of errors is empty if everything is OK.
1325 # @param theSubObject a sub-shape of a mesh shape
1326 # @return a list of errors
1327 # @ingroup l2_construct
1328 def GetAlgoState(self, theSubObject):
1329 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1331 ## Returns a geometrical object on which the given element was built.
1332 # The returned geometrical object, if not nil, is either found in the
1333 # study or published by this method with the given name
1334 # @param theElementID the id of the mesh element
1335 # @param theGeomName the user-defined name of the geometrical object
1336 # @return GEOM::GEOM_Object instance
1337 # @ingroup l2_construct
1338 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1339 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1341 ## Returns the mesh dimension depending on the dimension of the underlying shape
1342 # or, if the mesh is not based on any shape, basing on deimension of elements
1343 # @return mesh dimension as an integer value [0,3]
1344 # @ingroup l1_auxiliary
1345 def MeshDimension(self):
1346 if self.mesh.HasShapeToMesh():
1347 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1348 if len( shells ) > 0 :
1350 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1352 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1357 if self.NbVolumes() > 0: return 3
1358 if self.NbFaces() > 0: return 2
1359 if self.NbEdges() > 0: return 1
1362 ## Evaluates size of prospective mesh on a shape
1363 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1364 # To know predicted number of e.g. edges, inquire it this way
1365 # Evaluate()[ EnumToLong( Entity_Edge )]
1366 def Evaluate(self, geom=0):
1367 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1369 geom = self.mesh.GetShapeToMesh()
1372 return self.smeshpyD.Evaluate(self.mesh, geom)
1375 ## Computes the mesh and returns the status of the computation
1376 # @param geom geomtrical shape on which mesh data should be computed
1377 # @param discardModifs if True and the mesh has been edited since
1378 # a last total re-compute and that may prevent successful partial re-compute,
1379 # then the mesh is cleaned before Compute()
1380 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1381 # @return True or False
1382 # @ingroup l2_construct
1383 def Compute(self, geom=0, discardModifs=False, refresh=False):
1384 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1386 geom = self.mesh.GetShapeToMesh()
1391 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1393 ok = self.smeshpyD.Compute(self.mesh, geom)
1394 except SALOME.SALOME_Exception, ex:
1395 print "Mesh computation failed, exception caught:"
1396 print " ", ex.details.text
1399 print "Mesh computation failed, exception caught:"
1400 traceback.print_exc()
1404 # Treat compute errors
1405 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1406 for err in computeErrors:
1408 if self.mesh.HasShapeToMesh():
1410 mainIOR = salome.orb.object_to_string(geom)
1411 for sname in salome.myStudyManager.GetOpenStudies():
1412 s = salome.myStudyManager.GetStudyByName(sname)
1414 mainSO = s.FindObjectIOR(mainIOR)
1415 if not mainSO: continue
1416 if err.subShapeID == 1:
1417 shapeText = ' on "%s"' % mainSO.GetName()
1418 subIt = s.NewChildIterator(mainSO)
1420 subSO = subIt.Value()
1422 obj = subSO.GetObject()
1423 if not obj: continue
1424 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1426 ids = go.GetSubShapeIndices()
1427 if len(ids) == 1 and ids[0] == err.subShapeID:
1428 shapeText = ' on "%s"' % subSO.GetName()
1431 shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1433 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1435 shapeText = " on subshape #%s" % (err.subShapeID)
1437 shapeText = " on subshape #%s" % (err.subShapeID)
1439 stdErrors = ["OK", #COMPERR_OK
1440 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1441 "std::exception", #COMPERR_STD_EXCEPTION
1442 "OCC exception", #COMPERR_OCC_EXCEPTION
1443 "..", #COMPERR_SLM_EXCEPTION
1444 "Unknown exception", #COMPERR_EXCEPTION
1445 "Memory allocation problem", #COMPERR_MEMORY_PB
1446 "Algorithm failed", #COMPERR_ALGO_FAILED
1447 "Unexpected geometry", #COMPERR_BAD_SHAPE
1448 "Warning", #COMPERR_WARNING
1449 "Computation cancelled",#COMPERR_CANCELED
1450 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1452 if err.code < len(stdErrors): errText = stdErrors[err.code]
1454 errText = "code %s" % -err.code
1455 if errText: errText += ". "
1456 errText += err.comment
1457 if allReasons != "":allReasons += "\n"
1459 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1461 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1465 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1467 if err.isGlobalAlgo:
1475 reason = '%s %sD algorithm is missing' % (glob, dim)
1476 elif err.state == HYP_MISSING:
1477 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1478 % (glob, dim, name, dim))
1479 elif err.state == HYP_NOTCONFORM:
1480 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1481 elif err.state == HYP_BAD_PARAMETER:
1482 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1483 % ( glob, dim, name ))
1484 elif err.state == HYP_BAD_GEOMETRY:
1485 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1486 'geometry' % ( glob, dim, name ))
1487 elif err.state == HYP_HIDDEN_ALGO:
1488 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1489 'algorithm of upper dimension generating %sD mesh'
1490 % ( glob, dim, name, glob, dim ))
1492 reason = ("For unknown reason. "
1493 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1495 if allReasons != "":allReasons += "\n"
1496 allReasons += "- " + reason
1498 if not ok or allReasons != "":
1499 msg = '"' + GetName(self.mesh) + '"'
1500 if ok: msg += " has been computed with warnings"
1501 else: msg += " has not been computed"
1502 if allReasons != "": msg += ":"
1507 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1508 smeshgui = salome.ImportComponentGUI("SMESH")
1509 smeshgui.Init(self.mesh.GetStudyId())
1510 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1511 if refresh: salome.sg.updateObjBrowser(1)
1515 ## Return submesh objects list in meshing order
1516 # @return list of list of submesh objects
1517 # @ingroup l2_construct
1518 def GetMeshOrder(self):
1519 return self.mesh.GetMeshOrder()
1521 ## Return submesh objects list in meshing order
1522 # @return list of list of submesh objects
1523 # @ingroup l2_construct
1524 def SetMeshOrder(self, submeshes):
1525 return self.mesh.SetMeshOrder(submeshes)
1527 ## Removes all nodes and elements
1528 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1529 # @ingroup l2_construct
1530 def Clear(self, refresh=False):
1532 if ( salome.sg.hasDesktop() and
1533 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1534 smeshgui = salome.ImportComponentGUI("SMESH")
1535 smeshgui.Init(self.mesh.GetStudyId())
1536 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1537 if refresh: salome.sg.updateObjBrowser(1)
1539 ## Removes all nodes and elements of indicated shape
1540 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1541 # @param geomId the ID of a sub-shape to remove elements on
1542 # @ingroup l2_construct
1543 def ClearSubMesh(self, geomId, refresh=False):
1544 self.mesh.ClearSubMesh(geomId)
1545 if salome.sg.hasDesktop():
1546 smeshgui = salome.ImportComponentGUI("SMESH")
1547 smeshgui.Init(self.mesh.GetStudyId())
1548 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1549 if refresh: salome.sg.updateObjBrowser(1)
1551 ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1552 # @param fineness [0.0,1.0] defines mesh fineness
1553 # @return True or False
1554 # @ingroup l3_algos_basic
1555 def AutomaticTetrahedralization(self, fineness=0):
1556 dim = self.MeshDimension()
1558 self.RemoveGlobalHypotheses()
1559 self.Segment().AutomaticLength(fineness)
1561 self.Triangle().LengthFromEdges()
1566 return self.Compute()
1568 ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1569 # @param fineness [0.0, 1.0] defines mesh fineness
1570 # @return True or False
1571 # @ingroup l3_algos_basic
1572 def AutomaticHexahedralization(self, fineness=0):
1573 dim = self.MeshDimension()
1574 # assign the hypotheses
1575 self.RemoveGlobalHypotheses()
1576 self.Segment().AutomaticLength(fineness)
1583 return self.Compute()
1585 ## Assigns a hypothesis
1586 # @param hyp a hypothesis to assign
1587 # @param geom a subhape of mesh geometry
1588 # @return SMESH.Hypothesis_Status
1589 # @ingroup l2_hypotheses
1590 def AddHypothesis(self, hyp, geom=0):
1591 if isinstance( hyp, Mesh_Algorithm ):
1592 hyp = hyp.GetAlgorithm()
1597 geom = self.mesh.GetShapeToMesh()
1600 if self.mesh.HasShapeToMesh():
1601 hyp_type = hyp.GetName()
1602 lib_name = hyp.GetLibName()
1603 checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1604 if checkAll and geom:
1605 checkAll = geom.GetType() == 37
1606 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1608 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1609 status = self.mesh.AddHypothesis(geom, hyp)
1611 status = HYP_BAD_GEOMETRY,""
1612 hyp_name = GetName( hyp )
1615 geom_name = geom.GetName()
1616 isAlgo = hyp._narrow( SMESH_Algo )
1617 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1620 ## Return True if an algorithm of hypothesis is assigned to a given shape
1621 # @param hyp a hypothesis to check
1622 # @param geom a subhape of mesh geometry
1623 # @return True of False
1624 # @ingroup l2_hypotheses
1625 def IsUsedHypothesis(self, hyp, geom):
1626 if not hyp: # or not geom
1628 if isinstance( hyp, Mesh_Algorithm ):
1629 hyp = hyp.GetAlgorithm()
1631 hyps = self.GetHypothesisList(geom)
1633 if h.GetId() == hyp.GetId():
1637 ## Unassigns a hypothesis
1638 # @param hyp a hypothesis to unassign
1639 # @param geom a sub-shape of mesh geometry
1640 # @return SMESH.Hypothesis_Status
1641 # @ingroup l2_hypotheses
1642 def RemoveHypothesis(self, hyp, geom=0):
1645 if isinstance( hyp, Mesh_Algorithm ):
1646 hyp = hyp.GetAlgorithm()
1652 if self.IsUsedHypothesis( hyp, shape ):
1653 return self.mesh.RemoveHypothesis( shape, hyp )
1654 hypName = GetName( hyp )
1655 geoName = GetName( shape )
1656 print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1659 ## Gets the list of hypotheses added on a geometry
1660 # @param geom a sub-shape of mesh geometry
1661 # @return the sequence of SMESH_Hypothesis
1662 # @ingroup l2_hypotheses
1663 def GetHypothesisList(self, geom):
1664 return self.mesh.GetHypothesisList( geom )
1666 ## Removes all global hypotheses
1667 # @ingroup l2_hypotheses
1668 def RemoveGlobalHypotheses(self):
1669 current_hyps = self.mesh.GetHypothesisList( self.geom )
1670 for hyp in current_hyps:
1671 self.mesh.RemoveHypothesis( self.geom, hyp )
1675 ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1676 ## allowing to overwrite the file if it exists or add the exported data to its contents
1677 # @param f is the file name
1678 # @param auto_groups boolean parameter for creating/not creating
1679 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1680 # the typical use is auto_groups=false.
1681 # @param version MED format version(MED_V2_1 or MED_V2_2)
1682 # @param overwrite boolean parameter for overwriting/not overwriting the file
1683 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1684 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1685 # - 1D if all mesh nodes lie on OX coordinate axis, or
1686 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1687 # - 3D in the rest cases.
1688 # If @a autoDimension is @c False, the space dimension is always 3.
1689 # @param fields : list of GEOM fields defined on the shape to mesh.
1690 # @param geomAssocFields : each character of this string means a need to export a
1691 # corresponding field; correspondence between fields and characters is following:
1692 # - 'v' stands for _vertices_ field;
1693 # - 'e' stands for _edges_ field;
1694 # - 'f' stands for _faces_ field;
1695 # - 's' stands for _solids_ field.
1696 # @ingroup l2_impexp
1697 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1698 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1699 if meshPart or fields or geomAssocFields:
1700 unRegister = genObjUnRegister()
1701 if isinstance( meshPart, list ):
1702 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1703 unRegister.set( meshPart )
1704 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1705 fields, geomAssocFields)
1707 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1709 ## Exports the mesh in a file in SAUV format
1710 # @param f is the file name
1711 # @param auto_groups boolean parameter for creating/not creating
1712 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1713 # the typical use is auto_groups=false.
1714 # @ingroup l2_impexp
1715 def ExportSAUV(self, f, auto_groups=0):
1716 self.mesh.ExportSAUV(f, auto_groups)
1718 ## Exports the mesh in a file in DAT format
1719 # @param f the file name
1720 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1721 # @ingroup l2_impexp
1722 def ExportDAT(self, f, meshPart=None):
1724 unRegister = genObjUnRegister()
1725 if isinstance( meshPart, list ):
1726 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1727 unRegister.set( meshPart )
1728 self.mesh.ExportPartToDAT( meshPart, f )
1730 self.mesh.ExportDAT(f)
1732 ## Exports the mesh in a file in UNV format
1733 # @param f the file name
1734 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1735 # @ingroup l2_impexp
1736 def ExportUNV(self, f, meshPart=None):
1738 unRegister = genObjUnRegister()
1739 if isinstance( meshPart, list ):
1740 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1741 unRegister.set( meshPart )
1742 self.mesh.ExportPartToUNV( meshPart, f )
1744 self.mesh.ExportUNV(f)
1746 ## Export the mesh in a file in STL format
1747 # @param f the file name
1748 # @param ascii defines the file encoding
1749 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1750 # @ingroup l2_impexp
1751 def ExportSTL(self, f, ascii=1, meshPart=None):
1753 unRegister = genObjUnRegister()
1754 if isinstance( meshPart, list ):
1755 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1756 unRegister.set( meshPart )
1757 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1759 self.mesh.ExportSTL(f, ascii)
1761 ## Exports the mesh in a file in CGNS format
1762 # @param f is the file name
1763 # @param overwrite boolean parameter for overwriting/not overwriting the file
1764 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1765 # @ingroup l2_impexp
1766 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1767 unRegister = genObjUnRegister()
1768 if isinstance( meshPart, list ):
1769 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1770 unRegister.set( meshPart )
1771 if isinstance( meshPart, Mesh ):
1772 meshPart = meshPart.mesh
1774 meshPart = self.mesh
1775 self.mesh.ExportCGNS(meshPart, f, overwrite)
1777 ## Exports the mesh in a file in GMF format.
1778 # GMF files must have .mesh extension for the ASCII format and .meshb for
1779 # the bynary format. Other extensions are not allowed.
1780 # @param f is the file name
1781 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1782 # @ingroup l2_impexp
1783 def ExportGMF(self, f, meshPart=None):
1784 unRegister = genObjUnRegister()
1785 if isinstance( meshPart, list ):
1786 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1787 unRegister.set( meshPart )
1788 if isinstance( meshPart, Mesh ):
1789 meshPart = meshPart.mesh
1791 meshPart = self.mesh
1792 self.mesh.ExportGMF(meshPart, f, True)
1794 ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1795 # Exports the mesh in a file in MED format and chooses the \a version of MED format
1796 ## allowing to overwrite the file if it exists or add the exported data to its contents
1797 # @param f the file name
1798 # @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1799 # @param opt boolean parameter for creating/not creating
1800 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1801 # @param overwrite boolean parameter for overwriting/not overwriting the file
1802 # @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1803 # - 1D if all mesh nodes lie on OX coordinate axis, or
1804 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1805 # - 3D in the rest cases.
1807 # If @a autoDimension is @c False, the space dimension is always 3.
1808 # @ingroup l2_impexp
1809 def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1810 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1812 # Operations with groups:
1813 # ----------------------
1815 ## Creates an empty mesh group
1816 # @param elementType the type of elements in the group
1817 # @param name the name of the mesh group
1818 # @return SMESH_Group
1819 # @ingroup l2_grps_create
1820 def CreateEmptyGroup(self, elementType, name):
1821 return self.mesh.CreateGroup(elementType, name)
1823 ## Creates a mesh group based on the geometric object \a grp
1824 # and gives a \a name, \n if this parameter is not defined
1825 # the name is the same as the geometric group name \n
1826 # Note: Works like GroupOnGeom().
1827 # @param grp a geometric group, a vertex, an edge, a face or a solid
1828 # @param name the name of the mesh group
1829 # @return SMESH_GroupOnGeom
1830 # @ingroup l2_grps_create
1831 def Group(self, grp, name=""):
1832 return self.GroupOnGeom(grp, name)
1834 ## Creates a mesh group based on the geometrical object \a grp
1835 # and gives a \a name, \n if this parameter is not defined
1836 # the name is the same as the geometrical group name
1837 # @param grp a geometrical group, a vertex, an edge, a face or a solid
1838 # @param name the name of the mesh group
1839 # @param typ the type of elements in the group. If not set, it is
1840 # automatically detected by the type of the geometry
1841 # @return SMESH_GroupOnGeom
1842 # @ingroup l2_grps_create
1843 def GroupOnGeom(self, grp, name="", typ=None):
1844 AssureGeomPublished( self, grp, name )
1846 name = grp.GetName()
1848 typ = self._groupTypeFromShape( grp )
1849 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1851 ## Pivate method to get a type of group on geometry
1852 def _groupTypeFromShape( self, shape ):
1853 tgeo = str(shape.GetShapeType())
1854 if tgeo == "VERTEX":
1856 elif tgeo == "EDGE":
1858 elif tgeo == "FACE" or tgeo == "SHELL":
1860 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1862 elif tgeo == "COMPOUND":
1863 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1865 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1866 return self._groupTypeFromShape( sub[0] )
1869 "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1872 ## Creates a mesh group with given \a name based on the \a filter which
1873 ## is a special type of group dynamically updating it's contents during
1874 ## mesh modification
1875 # @param typ the type of elements in the group
1876 # @param name the name of the mesh group
1877 # @param filter the filter defining group contents
1878 # @return SMESH_GroupOnFilter
1879 # @ingroup l2_grps_create
1880 def GroupOnFilter(self, typ, name, filter):
1881 return self.mesh.CreateGroupFromFilter(typ, name, filter)
1883 ## Creates a mesh group by the given ids of elements
1884 # @param groupName the name of the mesh group
1885 # @param elementType the type of elements in the group
1886 # @param elemIDs the list of ids
1887 # @return SMESH_Group
1888 # @ingroup l2_grps_create
1889 def MakeGroupByIds(self, groupName, elementType, elemIDs):
1890 group = self.mesh.CreateGroup(elementType, groupName)
1891 if hasattr( elemIDs, "GetIDs" ):
1892 if hasattr( elemIDs, "SetMesh" ):
1893 elemIDs.SetMesh( self.GetMesh() )
1894 group.AddFrom( elemIDs )
1899 ## Creates a mesh group by the given conditions
1900 # @param groupName the name of the mesh group
1901 # @param elementType the type of elements in the group
1902 # @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1903 # @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1904 # @param Threshold the threshold value (range of id ids as string, shape, numeric)
1905 # @param UnaryOp FT_LogicalNOT or FT_Undefined
1906 # @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1907 # FT_LyingOnGeom, FT_CoplanarFaces criteria
1908 # @return SMESH_GroupOnFilter
1909 # @ingroup l2_grps_create
1913 CritType=FT_Undefined,
1916 UnaryOp=FT_Undefined,
1918 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1919 group = self.MakeGroupByCriterion(groupName, aCriterion)
1922 ## Creates a mesh group by the given criterion
1923 # @param groupName the name of the mesh group
1924 # @param Criterion the instance of Criterion class
1925 # @return SMESH_GroupOnFilter
1926 # @ingroup l2_grps_create
1927 def MakeGroupByCriterion(self, groupName, Criterion):
1928 return self.MakeGroupByCriteria( groupName, [Criterion] )
1930 ## Creates a mesh group by the given criteria (list of criteria)
1931 # @param groupName the name of the mesh group
1932 # @param theCriteria the list of criteria
1933 # @param binOp binary operator used when binary operator of criteria is undefined
1934 # @return SMESH_GroupOnFilter
1935 # @ingroup l2_grps_create
1936 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
1937 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
1938 group = self.MakeGroupByFilter(groupName, aFilter)
1941 ## Creates a mesh group by the given filter
1942 # @param groupName the name of the mesh group
1943 # @param theFilter the instance of Filter class
1944 # @return SMESH_GroupOnFilter
1945 # @ingroup l2_grps_create
1946 def MakeGroupByFilter(self, groupName, theFilter):
1947 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1948 #theFilter.SetMesh( self.mesh )
1949 #group.AddFrom( theFilter )
1950 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
1954 # @ingroup l2_grps_delete
1955 def RemoveGroup(self, group):
1956 self.mesh.RemoveGroup(group)
1958 ## Removes a group with its contents
1959 # @ingroup l2_grps_delete
1960 def RemoveGroupWithContents(self, group):
1961 self.mesh.RemoveGroupWithContents(group)
1963 ## Gets the list of groups existing in the mesh in the order of creation (starting from the oldest one)
1964 # @return a sequence of SMESH_GroupBase
1965 # @ingroup l2_grps_create
1966 def GetGroups(self):
1967 return self.mesh.GetGroups()
1969 ## Gets the number of groups existing in the mesh
1970 # @return the quantity of groups as an integer value
1971 # @ingroup l2_grps_create
1973 return self.mesh.NbGroups()
1975 ## Gets the list of names of groups existing in the mesh
1976 # @return list of strings
1977 # @ingroup l2_grps_create
1978 def GetGroupNames(self):
1979 groups = self.GetGroups()
1981 for group in groups:
1982 names.append(group.GetName())
1985 ## Produces a union of two groups
1986 # A new group is created. All mesh elements that are
1987 # present in the initial groups are added to the new one
1988 # @return an instance of SMESH_Group
1989 # @ingroup l2_grps_operon
1990 def UnionGroups(self, group1, group2, name):
1991 return self.mesh.UnionGroups(group1, group2, name)
1993 ## Produces a union list of groups
1994 # New group is created. All mesh elements that are present in
1995 # initial groups are added to the new one
1996 # @return an instance of SMESH_Group
1997 # @ingroup l2_grps_operon
1998 def UnionListOfGroups(self, groups, name):
1999 return self.mesh.UnionListOfGroups(groups, name)
2001 ## Prodices an intersection of two groups
2002 # A new group is created. All mesh elements that are common
2003 # for the two initial groups are added to the new one.
2004 # @return an instance of SMESH_Group
2005 # @ingroup l2_grps_operon
2006 def IntersectGroups(self, group1, group2, name):
2007 return self.mesh.IntersectGroups(group1, group2, name)
2009 ## Produces an intersection of groups
2010 # New group is created. All mesh elements that are present in all
2011 # initial groups simultaneously are added to the new one
2012 # @return an instance of SMESH_Group
2013 # @ingroup l2_grps_operon
2014 def IntersectListOfGroups(self, groups, name):
2015 return self.mesh.IntersectListOfGroups(groups, name)
2017 ## Produces a cut of two groups
2018 # A new group is created. All mesh elements that are present in
2019 # the main group but are not present in the tool group are added to the new one
2020 # @return an instance of SMESH_Group
2021 # @ingroup l2_grps_operon
2022 def CutGroups(self, main_group, tool_group, name):
2023 return self.mesh.CutGroups(main_group, tool_group, name)
2025 ## Produces a cut of groups
2026 # A new group is created. All mesh elements that are present in main groups
2027 # but do not present in tool groups are added to the new one
2028 # @return an instance of SMESH_Group
2029 # @ingroup l2_grps_operon
2030 def CutListOfGroups(self, main_groups, tool_groups, name):
2031 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2033 ## Produces a group of elements of specified type using list of existing groups
2034 # A new group is created. System
2035 # 1) extracts all nodes on which groups elements are built
2036 # 2) combines all elements of specified dimension laying on these nodes
2037 # @return an instance of SMESH_Group
2038 # @ingroup l2_grps_operon
2039 def CreateDimGroup(self, groups, elem_type, name):
2040 return self.mesh.CreateDimGroup(groups, elem_type, name)
2043 ## Convert group on geom into standalone group
2044 # @ingroup l2_grps_delete
2045 def ConvertToStandalone(self, group):
2046 return self.mesh.ConvertToStandalone(group)
2048 # Get some info about mesh:
2049 # ------------------------
2051 ## Returns the log of nodes and elements added or removed
2052 # since the previous clear of the log.
2053 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2054 # @return list of log_block structures:
2059 # @ingroup l1_auxiliary
2060 def GetLog(self, clearAfterGet):
2061 return self.mesh.GetLog(clearAfterGet)
2063 ## Clears the log of nodes and elements added or removed since the previous
2064 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2065 # @ingroup l1_auxiliary
2067 self.mesh.ClearLog()
2069 ## Toggles auto color mode on the object.
2070 # @param theAutoColor the flag which toggles auto color mode.
2071 # @ingroup l1_auxiliary
2072 def SetAutoColor(self, theAutoColor):
2073 self.mesh.SetAutoColor(theAutoColor)
2075 ## Gets flag of object auto color mode.
2076 # @return True or False
2077 # @ingroup l1_auxiliary
2078 def GetAutoColor(self):
2079 return self.mesh.GetAutoColor()
2081 ## Gets the internal ID
2082 # @return integer value, which is the internal Id of the mesh
2083 # @ingroup l1_auxiliary
2085 return self.mesh.GetId()
2088 # @return integer value, which is the study Id of the mesh
2089 # @ingroup l1_auxiliary
2090 def GetStudyId(self):
2091 return self.mesh.GetStudyId()
2093 ## Checks the group names for duplications.
2094 # Consider the maximum group name length stored in MED file.
2095 # @return True or False
2096 # @ingroup l1_auxiliary
2097 def HasDuplicatedGroupNamesMED(self):
2098 return self.mesh.HasDuplicatedGroupNamesMED()
2100 ## Obtains the mesh editor tool
2101 # @return an instance of SMESH_MeshEditor
2102 # @ingroup l1_modifying
2103 def GetMeshEditor(self):
2106 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2107 # can be passed as argument to a method accepting mesh, group or sub-mesh
2108 # @return an instance of SMESH_IDSource
2109 # @ingroup l1_auxiliary
2110 def GetIDSource(self, ids, elemType):
2111 return self.editor.MakeIDSource(ids, elemType)
2114 # Get informations about mesh contents:
2115 # ------------------------------------
2117 ## Gets the mesh stattistic
2118 # @return dictionary type element - count of elements
2119 # @ingroup l1_meshinfo
2120 def GetMeshInfo(self, obj = None):
2121 if not obj: obj = self.mesh
2122 return self.smeshpyD.GetMeshInfo(obj)
2124 ## Returns the number of nodes in the mesh
2125 # @return an integer value
2126 # @ingroup l1_meshinfo
2128 return self.mesh.NbNodes()
2130 ## Returns the number of elements in the mesh
2131 # @return an integer value
2132 # @ingroup l1_meshinfo
2133 def NbElements(self):
2134 return self.mesh.NbElements()
2136 ## Returns the number of 0d elements in the mesh
2137 # @return an integer value
2138 # @ingroup l1_meshinfo
2139 def Nb0DElements(self):
2140 return self.mesh.Nb0DElements()
2142 ## Returns the number of ball discrete elements in the mesh
2143 # @return an integer value
2144 # @ingroup l1_meshinfo
2146 return self.mesh.NbBalls()
2148 ## Returns the number of edges in the mesh
2149 # @return an integer value
2150 # @ingroup l1_meshinfo
2152 return self.mesh.NbEdges()
2154 ## Returns the number of edges with the given order in the mesh
2155 # @param elementOrder the order of elements:
2156 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2157 # @return an integer value
2158 # @ingroup l1_meshinfo
2159 def NbEdgesOfOrder(self, elementOrder):
2160 return self.mesh.NbEdgesOfOrder(elementOrder)
2162 ## Returns the number of faces in the mesh
2163 # @return an integer value
2164 # @ingroup l1_meshinfo
2166 return self.mesh.NbFaces()
2168 ## Returns the number of faces with the given order in the mesh
2169 # @param elementOrder the order of elements:
2170 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2171 # @return an integer value
2172 # @ingroup l1_meshinfo
2173 def NbFacesOfOrder(self, elementOrder):
2174 return self.mesh.NbFacesOfOrder(elementOrder)
2176 ## Returns the number of triangles in the mesh
2177 # @return an integer value
2178 # @ingroup l1_meshinfo
2179 def NbTriangles(self):
2180 return self.mesh.NbTriangles()
2182 ## Returns the number of triangles with the given order in the mesh
2183 # @param elementOrder is the order of elements:
2184 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2185 # @return an integer value
2186 # @ingroup l1_meshinfo
2187 def NbTrianglesOfOrder(self, elementOrder):
2188 return self.mesh.NbTrianglesOfOrder(elementOrder)
2190 ## Returns the number of biquadratic triangles in the mesh
2191 # @return an integer value
2192 # @ingroup l1_meshinfo
2193 def NbBiQuadTriangles(self):
2194 return self.mesh.NbBiQuadTriangles()
2196 ## Returns the number of quadrangles in the mesh
2197 # @return an integer value
2198 # @ingroup l1_meshinfo
2199 def NbQuadrangles(self):
2200 return self.mesh.NbQuadrangles()
2202 ## Returns the number of quadrangles with the given order in the mesh
2203 # @param elementOrder the order of elements:
2204 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2205 # @return an integer value
2206 # @ingroup l1_meshinfo
2207 def NbQuadranglesOfOrder(self, elementOrder):
2208 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2210 ## Returns the number of biquadratic quadrangles in the mesh
2211 # @return an integer value
2212 # @ingroup l1_meshinfo
2213 def NbBiQuadQuadrangles(self):
2214 return self.mesh.NbBiQuadQuadrangles()
2216 ## Returns the number of polygons in the mesh
2217 # @return an integer value
2218 # @ingroup l1_meshinfo
2219 def NbPolygons(self):
2220 return self.mesh.NbPolygons()
2222 ## Returns the number of volumes in the mesh
2223 # @return an integer value
2224 # @ingroup l1_meshinfo
2225 def NbVolumes(self):
2226 return self.mesh.NbVolumes()
2228 ## Returns the number of volumes with the given order in the mesh
2229 # @param elementOrder the order of elements:
2230 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2231 # @return an integer value
2232 # @ingroup l1_meshinfo
2233 def NbVolumesOfOrder(self, elementOrder):
2234 return self.mesh.NbVolumesOfOrder(elementOrder)
2236 ## Returns the number of tetrahedrons in the mesh
2237 # @return an integer value
2238 # @ingroup l1_meshinfo
2240 return self.mesh.NbTetras()
2242 ## Returns the number of tetrahedrons with the given order in the mesh
2243 # @param elementOrder the order of elements:
2244 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2245 # @return an integer value
2246 # @ingroup l1_meshinfo
2247 def NbTetrasOfOrder(self, elementOrder):
2248 return self.mesh.NbTetrasOfOrder(elementOrder)
2250 ## Returns the number of hexahedrons in the mesh
2251 # @return an integer value
2252 # @ingroup l1_meshinfo
2254 return self.mesh.NbHexas()
2256 ## Returns the number of hexahedrons with the given order in the mesh
2257 # @param elementOrder the order of elements:
2258 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2259 # @return an integer value
2260 # @ingroup l1_meshinfo
2261 def NbHexasOfOrder(self, elementOrder):
2262 return self.mesh.NbHexasOfOrder(elementOrder)
2264 ## Returns the number of triquadratic hexahedrons in the mesh
2265 # @return an integer value
2266 # @ingroup l1_meshinfo
2267 def NbTriQuadraticHexas(self):
2268 return self.mesh.NbTriQuadraticHexas()
2270 ## Returns the number of pyramids in the mesh
2271 # @return an integer value
2272 # @ingroup l1_meshinfo
2273 def NbPyramids(self):
2274 return self.mesh.NbPyramids()
2276 ## Returns the number of pyramids with the given order in the mesh
2277 # @param elementOrder the order of elements:
2278 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2279 # @return an integer value
2280 # @ingroup l1_meshinfo
2281 def NbPyramidsOfOrder(self, elementOrder):
2282 return self.mesh.NbPyramidsOfOrder(elementOrder)
2284 ## Returns the number of prisms in the mesh
2285 # @return an integer value
2286 # @ingroup l1_meshinfo
2288 return self.mesh.NbPrisms()
2290 ## Returns the number of prisms with the given order in the mesh
2291 # @param elementOrder the order of elements:
2292 # ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2293 # @return an integer value
2294 # @ingroup l1_meshinfo
2295 def NbPrismsOfOrder(self, elementOrder):
2296 return self.mesh.NbPrismsOfOrder(elementOrder)
2298 ## Returns the number of hexagonal prisms in the mesh
2299 # @return an integer value
2300 # @ingroup l1_meshinfo
2301 def NbHexagonalPrisms(self):
2302 return self.mesh.NbHexagonalPrisms()
2304 ## Returns the number of polyhedrons in the mesh
2305 # @return an integer value
2306 # @ingroup l1_meshinfo
2307 def NbPolyhedrons(self):
2308 return self.mesh.NbPolyhedrons()
2310 ## Returns the number of submeshes in the mesh
2311 # @return an integer value
2312 # @ingroup l1_meshinfo
2313 def NbSubMesh(self):
2314 return self.mesh.NbSubMesh()
2316 ## Returns the list of mesh elements IDs
2317 # @return the list of integer values
2318 # @ingroup l1_meshinfo
2319 def GetElementsId(self):
2320 return self.mesh.GetElementsId()
2322 ## Returns the list of IDs of mesh elements with the given type
2323 # @param elementType the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2324 # @return list of integer values
2325 # @ingroup l1_meshinfo
2326 def GetElementsByType(self, elementType):
2327 return self.mesh.GetElementsByType(elementType)
2329 ## Returns the list of mesh nodes IDs
2330 # @return the list of integer values
2331 # @ingroup l1_meshinfo
2332 def GetNodesId(self):
2333 return self.mesh.GetNodesId()
2335 # Get the information about mesh elements:
2336 # ------------------------------------
2338 ## Returns the type of mesh element
2339 # @return the value from SMESH::ElementType enumeration
2340 # @ingroup l1_meshinfo
2341 def GetElementType(self, id, iselem):
2342 return self.mesh.GetElementType(id, iselem)
2344 ## Returns the geometric type of mesh element
2345 # @return the value from SMESH::EntityType enumeration
2346 # @ingroup l1_meshinfo
2347 def GetElementGeomType(self, id):
2348 return self.mesh.GetElementGeomType(id)
2350 ## Returns the shape type of mesh element
2351 # @return the value from SMESH::GeometryType enumeration
2352 # @ingroup l1_meshinfo
2353 def GetElementShape(self, id):
2354 return self.mesh.GetElementShape(id)
2356 ## Returns the list of submesh elements IDs
2357 # @param Shape a geom object(sub-shape) IOR
2358 # Shape must be the sub-shape of a ShapeToMesh()
2359 # @return the list of integer values
2360 # @ingroup l1_meshinfo
2361 def GetSubMeshElementsId(self, Shape):
2362 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2363 ShapeID = Shape.GetSubShapeIndices()[0]
2366 return self.mesh.GetSubMeshElementsId(ShapeID)
2368 ## Returns the list of submesh nodes IDs
2369 # @param Shape a geom object(sub-shape) IOR
2370 # Shape must be the sub-shape of a ShapeToMesh()
2371 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2372 # @return the list of integer values
2373 # @ingroup l1_meshinfo
2374 def GetSubMeshNodesId(self, Shape, all):
2375 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2376 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2379 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2381 ## Returns type of elements on given shape
2382 # @param Shape a geom object(sub-shape) IOR
2383 # Shape must be a sub-shape of a ShapeToMesh()
2384 # @return element type
2385 # @ingroup l1_meshinfo
2386 def GetSubMeshElementType(self, Shape):
2387 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2388 ShapeID = Shape.GetSubShapeIndices()[0]
2391 return self.mesh.GetSubMeshElementType(ShapeID)
2393 ## Gets the mesh description
2394 # @return string value
2395 # @ingroup l1_meshinfo
2397 return self.mesh.Dump()
2400 # Get the information about nodes and elements of a mesh by its IDs:
2401 # -----------------------------------------------------------
2403 ## Gets XYZ coordinates of a node
2404 # \n If there is no nodes for the given ID - returns an empty list
2405 # @return a list of double precision values
2406 # @ingroup l1_meshinfo
2407 def GetNodeXYZ(self, id):
2408 return self.mesh.GetNodeXYZ(id)
2410 ## Returns list of IDs of inverse elements for the given node
2411 # \n If there is no node for the given ID - returns an empty list
2412 # @return a list of integer values
2413 # @ingroup l1_meshinfo
2414 def GetNodeInverseElements(self, id):
2415 return self.mesh.GetNodeInverseElements(id)
2417 ## @brief Returns the position of a node on the shape
2418 # @return SMESH::NodePosition
2419 # @ingroup l1_meshinfo
2420 def GetNodePosition(self,NodeID):
2421 return self.mesh.GetNodePosition(NodeID)
2423 ## @brief Returns the position of an element on the shape
2424 # @return SMESH::ElementPosition
2425 # @ingroup l1_meshinfo
2426 def GetElementPosition(self,ElemID):
2427 return self.mesh.GetElementPosition(ElemID)
2429 ## If the given element is a node, returns the ID of shape
2430 # \n If there is no node for the given ID - returns -1
2431 # @return an integer value
2432 # @ingroup l1_meshinfo
2433 def GetShapeID(self, id):
2434 return self.mesh.GetShapeID(id)
2436 ## Returns the ID of the result shape after
2437 # FindShape() from SMESH_MeshEditor for the given element
2438 # \n If there is no element for the given ID - returns -1
2439 # @return an integer value
2440 # @ingroup l1_meshinfo
2441 def GetShapeIDForElem(self,id):
2442 return self.mesh.GetShapeIDForElem(id)
2444 ## Returns the number of nodes for the given element
2445 # \n If there is no element for the given ID - returns -1
2446 # @return an integer value
2447 # @ingroup l1_meshinfo
2448 def GetElemNbNodes(self, id):
2449 return self.mesh.GetElemNbNodes(id)
2451 ## Returns the node ID the given (zero based) index for the given element
2452 # \n If there is no element for the given ID - returns -1
2453 # \n If there is no node for the given index - returns -2
2454 # @return an integer value
2455 # @ingroup l1_meshinfo
2456 def GetElemNode(self, id, index):
2457 return self.mesh.GetElemNode(id, index)
2459 ## Returns the IDs of nodes of the given element
2460 # @return a list of integer values
2461 # @ingroup l1_meshinfo
2462 def GetElemNodes(self, id):
2463 return self.mesh.GetElemNodes(id)
2465 ## Returns true if the given node is the medium node in the given quadratic element
2466 # @ingroup l1_meshinfo
2467 def IsMediumNode(self, elementID, nodeID):
2468 return self.mesh.IsMediumNode(elementID, nodeID)
2470 ## Returns true if the given node is the medium node in one of quadratic elements
2471 # @ingroup l1_meshinfo
2472 def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2473 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2475 ## Returns the number of edges for the given element
2476 # @ingroup l1_meshinfo
2477 def ElemNbEdges(self, id):
2478 return self.mesh.ElemNbEdges(id)
2480 ## Returns the number of faces for the given element
2481 # @ingroup l1_meshinfo
2482 def ElemNbFaces(self, id):
2483 return self.mesh.ElemNbFaces(id)
2485 ## Returns nodes of given face (counted from zero) for given volumic element.
2486 # @ingroup l1_meshinfo
2487 def GetElemFaceNodes(self,elemId, faceIndex):
2488 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2490 ## Returns three components of normal of given mesh face
2491 # (or an empty array in KO case)
2492 # @ingroup l1_meshinfo
2493 def GetFaceNormal(self, faceId, normalized=False):
2494 return self.mesh.GetFaceNormal(faceId,normalized)
2496 ## Returns an element based on all given nodes.
2497 # @ingroup l1_meshinfo
2498 def FindElementByNodes(self,nodes):
2499 return self.mesh.FindElementByNodes(nodes)
2501 ## Returns true if the given element is a polygon
2502 # @ingroup l1_meshinfo
2503 def IsPoly(self, id):
2504 return self.mesh.IsPoly(id)
2506 ## Returns true if the given element is quadratic
2507 # @ingroup l1_meshinfo
2508 def IsQuadratic(self, id):
2509 return self.mesh.IsQuadratic(id)
2511 ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2512 # @ingroup l1_meshinfo
2513 def GetBallDiameter(self, id):
2514 return self.mesh.GetBallDiameter(id)
2516 ## Returns XYZ coordinates of the barycenter of the given element
2517 # \n If there is no element for the given ID - returns an empty list
2518 # @return a list of three double values
2519 # @ingroup l1_meshinfo
2520 def BaryCenter(self, id):
2521 return self.mesh.BaryCenter(id)
2523 ## Passes mesh elements through the given filter and return IDs of fitting elements
2524 # @param theFilter SMESH_Filter
2525 # @return a list of ids
2526 # @ingroup l1_controls
2527 def GetIdsFromFilter(self, theFilter):
2528 theFilter.SetMesh( self.mesh )
2529 return theFilter.GetIDs()
2531 ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2532 # Returns a list of special structures (borders).
2533 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2534 # @ingroup l1_controls
2535 def GetFreeBorders(self):
2536 aFilterMgr = self.smeshpyD.CreateFilterManager()
2537 aPredicate = aFilterMgr.CreateFreeEdges()
2538 aPredicate.SetMesh(self.mesh)
2539 aBorders = aPredicate.GetBorders()
2540 aFilterMgr.UnRegister()
2544 # Get mesh measurements information:
2545 # ------------------------------------
2547 ## Get minimum distance between two nodes, elements or distance to the origin
2548 # @param id1 first node/element id
2549 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2550 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2551 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2552 # @return minimum distance value
2553 # @sa GetMinDistance()
2554 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2555 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2556 return aMeasure.value
2558 ## Get measure structure specifying minimum distance data between two objects
2559 # @param id1 first node/element id
2560 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2561 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2562 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2563 # @return Measure structure
2565 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2567 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2569 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2572 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2574 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2579 aMeasurements = self.smeshpyD.CreateMeasurements()
2580 aMeasure = aMeasurements.MinDistance(id1, id2)
2581 genObjUnRegister([aMeasurements,id1, id2])
2584 ## Get bounding box of the specified object(s)
2585 # @param objects single source object or list of source objects or list of nodes/elements IDs
2586 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2587 # @c False specifies that @a objects are nodes
2588 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2589 # @sa GetBoundingBox()
2590 def BoundingBox(self, objects=None, isElem=False):
2591 result = self.GetBoundingBox(objects, isElem)
2595 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2598 ## Get measure structure specifying bounding box data of the specified object(s)
2599 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2600 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2601 # @c False specifies that @a objects are nodes
2602 # @return Measure structure
2604 def GetBoundingBox(self, IDs=None, isElem=False):
2607 elif isinstance(IDs, tuple):
2609 if not isinstance(IDs, list):
2611 if len(IDs) > 0 and isinstance(IDs[0], int):
2614 unRegister = genObjUnRegister()
2616 if isinstance(o, Mesh):
2617 srclist.append(o.mesh)
2618 elif hasattr(o, "_narrow"):
2619 src = o._narrow(SMESH.SMESH_IDSource)
2620 if src: srclist.append(src)
2622 elif isinstance(o, list):
2624 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2626 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2627 unRegister.set( srclist[-1] )
2630 aMeasurements = self.smeshpyD.CreateMeasurements()
2631 unRegister.set( aMeasurements )
2632 aMeasure = aMeasurements.BoundingBox(srclist)
2635 # Mesh edition (SMESH_MeshEditor functionality):
2636 # ---------------------------------------------
2638 ## Removes the elements from the mesh by ids
2639 # @param IDsOfElements is a list of ids of elements to remove
2640 # @return True or False
2641 # @ingroup l2_modif_del
2642 def RemoveElements(self, IDsOfElements):
2643 return self.editor.RemoveElements(IDsOfElements)
2645 ## Removes nodes from mesh by ids
2646 # @param IDsOfNodes is a list of ids of nodes to remove
2647 # @return True or False
2648 # @ingroup l2_modif_del
2649 def RemoveNodes(self, IDsOfNodes):
2650 return self.editor.RemoveNodes(IDsOfNodes)
2652 ## Removes all orphan (free) nodes from mesh
2653 # @return number of the removed nodes
2654 # @ingroup l2_modif_del
2655 def RemoveOrphanNodes(self):
2656 return self.editor.RemoveOrphanNodes()
2658 ## Add a node to the mesh by coordinates
2659 # @return Id of the new node
2660 # @ingroup l2_modif_add
2661 def AddNode(self, x, y, z):
2662 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2663 if hasVars: self.mesh.SetParameters(Parameters)
2664 return self.editor.AddNode( x, y, z)
2666 ## Creates a 0D element on a node with given number.
2667 # @param IDOfNode the ID of node for creation of the element.
2668 # @return the Id of the new 0D element
2669 # @ingroup l2_modif_add
2670 def Add0DElement(self, IDOfNode):
2671 return self.editor.Add0DElement(IDOfNode)
2673 ## Create 0D elements on all nodes of the given elements except those
2674 # nodes on which a 0D element already exists.
2675 # @param theObject an object on whose nodes 0D elements will be created.
2676 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2677 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2678 # @param theGroupName optional name of a group to add 0D elements created
2679 # and/or found on nodes of \a theObject.
2680 # @return an object (a new group or a temporary SMESH_IDSource) holding
2681 # IDs of new and/or found 0D elements. IDs of 0D elements
2682 # can be retrieved from the returned object by calling GetIDs()
2683 # @ingroup l2_modif_add
2684 def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2685 unRegister = genObjUnRegister()
2686 if isinstance( theObject, Mesh ):
2687 theObject = theObject.GetMesh()
2688 if isinstance( theObject, list ):
2689 theObject = self.GetIDSource( theObject, SMESH.ALL )
2690 unRegister.set( theObject )
2691 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2693 ## Creates a ball element on a node with given ID.
2694 # @param IDOfNode the ID of node for creation of the element.
2695 # @param diameter the bal diameter.
2696 # @return the Id of the new ball element
2697 # @ingroup l2_modif_add
2698 def AddBall(self, IDOfNode, diameter):
2699 return self.editor.AddBall( IDOfNode, diameter )
2701 ## Creates a linear or quadratic edge (this is determined
2702 # by the number of given nodes).
2703 # @param IDsOfNodes the list of node IDs for creation of the element.
2704 # The order of nodes in this list should correspond to the description
2705 # of MED. \n This description is located by the following link:
2706 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2707 # @return the Id of the new edge
2708 # @ingroup l2_modif_add
2709 def AddEdge(self, IDsOfNodes):
2710 return self.editor.AddEdge(IDsOfNodes)
2712 ## Creates a linear or quadratic face (this is determined
2713 # by the number of given nodes).
2714 # @param IDsOfNodes the list of node IDs for creation of the element.
2715 # The order of nodes in this list should correspond to the description
2716 # of MED. \n This description is located by the following link:
2717 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2718 # @return the Id of the new face
2719 # @ingroup l2_modif_add
2720 def AddFace(self, IDsOfNodes):
2721 return self.editor.AddFace(IDsOfNodes)
2723 ## Adds a polygonal face to the mesh by the list of node IDs
2724 # @param IdsOfNodes the list of node IDs for creation of the element.
2725 # @return the Id of the new face
2726 # @ingroup l2_modif_add
2727 def AddPolygonalFace(self, IdsOfNodes):
2728 return self.editor.AddPolygonalFace(IdsOfNodes)
2730 ## Creates both simple and quadratic volume (this is determined
2731 # by the number of given nodes).
2732 # @param IDsOfNodes the list of node IDs for creation of the element.
2733 # The order of nodes in this list should correspond to the description
2734 # of MED. \n This description is located by the following link:
2735 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2736 # @return the Id of the new volumic element
2737 # @ingroup l2_modif_add
2738 def AddVolume(self, IDsOfNodes):
2739 return self.editor.AddVolume(IDsOfNodes)
2741 ## Creates a volume of many faces, giving nodes for each face.
2742 # @param IdsOfNodes the list of node IDs for volume creation face by face.
2743 # @param Quantities the list of integer values, Quantities[i]
2744 # gives the quantity of nodes in face number i.
2745 # @return the Id of the new volumic element
2746 # @ingroup l2_modif_add
2747 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2748 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2750 ## Creates a volume of many faces, giving the IDs of the existing faces.
2751 # @param IdsOfFaces the list of face IDs for volume creation.
2753 # Note: The created volume will refer only to the nodes
2754 # of the given faces, not to the faces themselves.
2755 # @return the Id of the new volumic element
2756 # @ingroup l2_modif_add
2757 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2758 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2761 ## @brief Binds a node to a vertex
2762 # @param NodeID a node ID
2763 # @param Vertex a vertex or vertex ID
2764 # @return True if succeed else raises an exception
2765 # @ingroup l2_modif_add
2766 def SetNodeOnVertex(self, NodeID, Vertex):
2767 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2768 VertexID = Vertex.GetSubShapeIndices()[0]
2772 self.editor.SetNodeOnVertex(NodeID, VertexID)
2773 except SALOME.SALOME_Exception, inst:
2774 raise ValueError, inst.details.text
2778 ## @brief Stores the node position on an edge
2779 # @param NodeID a node ID
2780 # @param Edge an edge or edge ID
2781 # @param paramOnEdge a parameter on the edge where the node is located
2782 # @return True if succeed else raises an exception
2783 # @ingroup l2_modif_add
2784 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2785 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2786 EdgeID = Edge.GetSubShapeIndices()[0]
2790 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2791 except SALOME.SALOME_Exception, inst:
2792 raise ValueError, inst.details.text
2795 ## @brief Stores node position on a face
2796 # @param NodeID a node ID
2797 # @param Face a face or face ID
2798 # @param u U parameter on the face where the node is located
2799 # @param v V parameter on the face where the node is located
2800 # @return True if succeed else raises an exception
2801 # @ingroup l2_modif_add
2802 def SetNodeOnFace(self, NodeID, Face, u, v):
2803 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2804 FaceID = Face.GetSubShapeIndices()[0]
2808 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2809 except SALOME.SALOME_Exception, inst:
2810 raise ValueError, inst.details.text
2813 ## @brief Binds a node to a solid
2814 # @param NodeID a node ID
2815 # @param Solid a solid or solid ID
2816 # @return True if succeed else raises an exception
2817 # @ingroup l2_modif_add
2818 def SetNodeInVolume(self, NodeID, Solid):
2819 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2820 SolidID = Solid.GetSubShapeIndices()[0]
2824 self.editor.SetNodeInVolume(NodeID, SolidID)
2825 except SALOME.SALOME_Exception, inst:
2826 raise ValueError, inst.details.text
2829 ## @brief Bind an element to a shape
2830 # @param ElementID an element ID
2831 # @param Shape a shape or shape ID
2832 # @return True if succeed else raises an exception
2833 # @ingroup l2_modif_add
2834 def SetMeshElementOnShape(self, ElementID, Shape):
2835 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2836 ShapeID = Shape.GetSubShapeIndices()[0]
2840 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2841 except SALOME.SALOME_Exception, inst:
2842 raise ValueError, inst.details.text
2846 ## Moves the node with the given id
2847 # @param NodeID the id of the node
2848 # @param x a new X coordinate
2849 # @param y a new Y coordinate
2850 # @param z a new Z coordinate
2851 # @return True if succeed else False
2852 # @ingroup l2_modif_movenode
2853 def MoveNode(self, NodeID, x, y, z):
2854 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2855 if hasVars: self.mesh.SetParameters(Parameters)
2856 return self.editor.MoveNode(NodeID, x, y, z)
2858 ## Finds the node closest to a point and moves it to a point location
2859 # @param x the X coordinate of a point
2860 # @param y the Y coordinate of a point
2861 # @param z the Z coordinate of a point
2862 # @param NodeID if specified (>0), the node with this ID is moved,
2863 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
2864 # @return the ID of a node
2865 # @ingroup l2_modif_throughp
2866 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2867 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2868 if hasVars: self.mesh.SetParameters(Parameters)
2869 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2871 ## Finds the node closest to a point
2872 # @param x the X coordinate of a point
2873 # @param y the Y coordinate of a point
2874 # @param z the Z coordinate of a point
2875 # @return the ID of a node
2876 # @ingroup l2_modif_throughp
2877 def FindNodeClosestTo(self, x, y, z):
2878 #preview = self.mesh.GetMeshEditPreviewer()
2879 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2880 return self.editor.FindNodeClosestTo(x, y, z)
2882 ## Finds the elements where a point lays IN or ON
2883 # @param x the X coordinate of a point
2884 # @param y the Y coordinate of a point
2885 # @param z the Z coordinate of a point
2886 # @param elementType type of elements to find (SMESH.ALL type
2887 # means elements of any type excluding nodes, discrete and 0D elements)
2888 # @param meshPart a part of mesh (group, sub-mesh) to search within
2889 # @return list of IDs of found elements
2890 # @ingroup l2_modif_throughp
2891 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2893 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2895 return self.editor.FindElementsByPoint(x, y, z, elementType)
2897 # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2898 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2899 # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2901 def GetPointState(self, x, y, z):
2902 return self.editor.GetPointState(x, y, z)
2904 ## Finds the node closest to a point and moves it to a point location
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 # @return the ID of a moved node
2909 # @ingroup l2_modif_throughp
2910 def MeshToPassThroughAPoint(self, x, y, z):
2911 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2913 ## Replaces two neighbour triangles sharing Node1-Node2 link
2914 # with the triangles built on the same 4 nodes but having other common link.
2915 # @param NodeID1 the ID of the first node
2916 # @param NodeID2 the ID of the second node
2917 # @return false if proper faces were not found
2918 # @ingroup l2_modif_invdiag
2919 def InverseDiag(self, NodeID1, NodeID2):
2920 return self.editor.InverseDiag(NodeID1, NodeID2)
2922 ## Replaces two neighbour triangles sharing Node1-Node2 link
2923 # with a quadrangle built on the same 4 nodes.
2924 # @param NodeID1 the ID of the first node
2925 # @param NodeID2 the ID of the second node
2926 # @return false if proper faces were not found
2927 # @ingroup l2_modif_unitetri
2928 def DeleteDiag(self, NodeID1, NodeID2):
2929 return self.editor.DeleteDiag(NodeID1, NodeID2)
2931 ## Reorients elements by ids
2932 # @param IDsOfElements if undefined reorients all mesh elements
2933 # @return True if succeed else False
2934 # @ingroup l2_modif_changori
2935 def Reorient(self, IDsOfElements=None):
2936 if IDsOfElements == None:
2937 IDsOfElements = self.GetElementsId()
2938 return self.editor.Reorient(IDsOfElements)
2940 ## Reorients all elements of the object
2941 # @param theObject mesh, submesh or group
2942 # @return True if succeed else False
2943 # @ingroup l2_modif_changori
2944 def ReorientObject(self, theObject):
2945 if ( isinstance( theObject, Mesh )):
2946 theObject = theObject.GetMesh()
2947 return self.editor.ReorientObject(theObject)
2949 ## Reorient faces contained in \a the2DObject.
2950 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2951 # @param theDirection is a desired direction of normal of \a theFace.
2952 # It can be either a GEOM vector or a list of coordinates [x,y,z].
2953 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2954 # compared with theDirection. It can be either ID of face or a point
2955 # by which the face will be found. The point can be given as either
2956 # a GEOM vertex or a list of point coordinates.
2957 # @return number of reoriented faces
2958 # @ingroup l2_modif_changori
2959 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2960 unRegister = genObjUnRegister()
2962 if isinstance( the2DObject, Mesh ):
2963 the2DObject = the2DObject.GetMesh()
2964 if isinstance( the2DObject, list ):
2965 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2966 unRegister.set( the2DObject )
2967 # check theDirection
2968 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2969 theDirection = self.smeshpyD.GetDirStruct( theDirection )
2970 if isinstance( theDirection, list ):
2971 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
2972 # prepare theFace and thePoint
2973 theFace = theFaceOrPoint
2974 thePoint = PointStruct(0,0,0)
2975 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2976 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2978 if isinstance( theFaceOrPoint, list ):
2979 thePoint = PointStruct( *theFaceOrPoint )
2981 if isinstance( theFaceOrPoint, PointStruct ):
2982 thePoint = theFaceOrPoint
2984 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2986 ## Reorient faces according to adjacent volumes.
2987 # @param the2DObject is a mesh, sub-mesh, group or list of
2988 # either IDs of faces or face groups.
2989 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
2990 # @param theOutsideNormal to orient faces to have their normals
2991 # pointing either \a outside or \a inside the adjacent volumes.
2992 # @return number of reoriented faces.
2993 # @ingroup l2_modif_changori
2994 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
2995 unRegister = genObjUnRegister()
2997 if not isinstance( the2DObject, list ):
2998 the2DObject = [ the2DObject ]
2999 elif the2DObject and isinstance( the2DObject[0], int ):
3000 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3001 unRegister.set( the2DObject )
3002 the2DObject = [ the2DObject ]
3003 for i,obj2D in enumerate( the2DObject ):
3004 if isinstance( obj2D, Mesh ):
3005 the2DObject[i] = obj2D.GetMesh()
3006 if isinstance( obj2D, list ):
3007 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3008 unRegister.set( the2DObject[i] )
3010 if isinstance( the3DObject, Mesh ):
3011 the3DObject = the3DObject.GetMesh()
3012 if isinstance( the3DObject, list ):
3013 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3014 unRegister.set( the3DObject )
3015 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3017 ## Fuses the neighbouring triangles into quadrangles.
3018 # @param IDsOfElements The triangles to be fused,
3019 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3020 # choose a neighbour to fuse with.
3021 # @param MaxAngle is the maximum angle between element normals at which the fusion
3022 # is still performed; theMaxAngle is mesured in radians.
3023 # Also it could be a name of variable which defines angle in degrees.
3024 # @return TRUE in case of success, FALSE otherwise.
3025 # @ingroup l2_modif_unitetri
3026 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3027 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3028 self.mesh.SetParameters(Parameters)
3029 if not IDsOfElements:
3030 IDsOfElements = self.GetElementsId()
3031 Functor = self.smeshpyD.GetFunctor(theCriterion)
3032 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3034 ## Fuses the neighbouring triangles of the object into quadrangles
3035 # @param theObject is mesh, submesh or group
3036 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3037 # choose a neighbour to fuse with.
3038 # @param MaxAngle a max angle between element normals at which the fusion
3039 # is still performed; theMaxAngle is mesured in radians.
3040 # @return TRUE in case of success, FALSE otherwise.
3041 # @ingroup l2_modif_unitetri
3042 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3043 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3044 self.mesh.SetParameters(Parameters)
3045 if isinstance( theObject, Mesh ):
3046 theObject = theObject.GetMesh()
3047 Functor = self.smeshpyD.GetFunctor(theCriterion)
3048 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3050 ## Splits quadrangles into triangles.
3051 # @param IDsOfElements the faces to be splitted.
3052 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3053 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3054 # value, then quadrangles will be split by the smallest diagonal.
3055 # @return TRUE in case of success, FALSE otherwise.
3056 # @ingroup l2_modif_cutquadr
3057 def QuadToTri (self, IDsOfElements, theCriterion = None):
3058 if IDsOfElements == []:
3059 IDsOfElements = self.GetElementsId()
3060 if theCriterion is None:
3061 theCriterion = FT_MaxElementLength2D
3062 Functor = self.smeshpyD.GetFunctor(theCriterion)
3063 return self.editor.QuadToTri(IDsOfElements, Functor)
3065 ## Splits quadrangles into triangles.
3066 # @param theObject the object from which the list of elements is taken,
3067 # this is mesh, submesh or group
3068 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3069 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3070 # value, then quadrangles will be split by the smallest diagonal.
3071 # @return TRUE in case of success, FALSE otherwise.
3072 # @ingroup l2_modif_cutquadr
3073 def QuadToTriObject (self, theObject, theCriterion = None):
3074 if ( isinstance( theObject, Mesh )):
3075 theObject = theObject.GetMesh()
3076 if theCriterion is None:
3077 theCriterion = FT_MaxElementLength2D
3078 Functor = self.smeshpyD.GetFunctor(theCriterion)
3079 return self.editor.QuadToTriObject(theObject, Functor)
3081 ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3083 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3084 # group or a list of face IDs. By default all quadrangles are split
3085 # @ingroup l2_modif_cutquadr
3086 def QuadTo4Tri (self, theElements=[]):
3087 unRegister = genObjUnRegister()
3088 if isinstance( theElements, Mesh ):
3089 theElements = theElements.mesh
3090 elif not theElements:
3091 theElements = self.mesh
3092 elif isinstance( theElements, list ):
3093 theElements = self.GetIDSource( theElements, SMESH.FACE )
3094 unRegister.set( theElements )
3095 return self.editor.QuadTo4Tri( theElements )
3097 ## Splits quadrangles into triangles.
3098 # @param IDsOfElements the faces to be splitted
3099 # @param Diag13 is used to choose a diagonal for splitting.
3100 # @return TRUE in case of success, FALSE otherwise.
3101 # @ingroup l2_modif_cutquadr
3102 def SplitQuad (self, IDsOfElements, Diag13):
3103 if IDsOfElements == []:
3104 IDsOfElements = self.GetElementsId()
3105 return self.editor.SplitQuad(IDsOfElements, Diag13)
3107 ## Splits quadrangles into triangles.
3108 # @param theObject the object from which the list of elements is taken,
3109 # this is mesh, submesh or group
3110 # @param Diag13 is used to choose a diagonal for splitting.
3111 # @return TRUE in case of success, FALSE otherwise.
3112 # @ingroup l2_modif_cutquadr
3113 def SplitQuadObject (self, theObject, Diag13):
3114 if ( isinstance( theObject, Mesh )):
3115 theObject = theObject.GetMesh()
3116 return self.editor.SplitQuadObject(theObject, Diag13)
3118 ## Finds a better splitting of the given quadrangle.
3119 # @param IDOfQuad the ID of the quadrangle to be splitted.
3120 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3121 # choose a diagonal for splitting.
3122 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3123 # diagonal is better, 0 if error occurs.
3124 # @ingroup l2_modif_cutquadr
3125 def BestSplit (self, IDOfQuad, theCriterion):
3126 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3128 ## Splits volumic elements into tetrahedrons
3129 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3130 # @param method flags passing splitting method:
3131 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3132 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3133 # @ingroup l2_modif_cutquadr
3134 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3135 unRegister = genObjUnRegister()
3136 if isinstance( elems, Mesh ):
3137 elems = elems.GetMesh()
3138 if ( isinstance( elems, list )):
3139 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3140 unRegister.set( elems )
3141 self.editor.SplitVolumesIntoTetra(elems, method)
3143 ## Splits hexahedra into prisms
3144 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3145 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3146 # gives a normal vector defining facets to split into triangles.
3147 # @a startHexPoint can be either a triple of coordinates or a vertex.
3148 # @param facetNormal a normal to a facet to split into triangles of a
3149 # hexahedron found by @a startHexPoint.
3150 # @a facetNormal can be either a triple of coordinates or an edge.
3151 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3152 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3153 # @param allDomains if @c False, only hexahedra adjacent to one closest
3154 # to @a startHexPoint are split, else @a startHexPoint
3155 # is used to find the facet to split in all domains present in @a elems.
3156 # @ingroup l2_modif_cutquadr
3157 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3158 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3160 unRegister = genObjUnRegister()
3161 if isinstance( elems, Mesh ):
3162 elems = elems.GetMesh()
3163 if ( isinstance( elems, list )):
3164 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3165 unRegister.set( elems )
3168 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3169 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3170 elif isinstance( startHexPoint, list ):
3171 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3174 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3175 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3176 elif isinstance( facetNormal, list ):
3177 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3180 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3182 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3184 ## Splits quadrangle faces near triangular facets of volumes
3186 # @ingroup l1_auxiliary
3187 def SplitQuadsNearTriangularFacets(self):
3188 faces_array = self.GetElementsByType(SMESH.FACE)
3189 for face_id in faces_array:
3190 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3191 quad_nodes = self.mesh.GetElemNodes(face_id)
3192 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3193 isVolumeFound = False
3194 for node1_elem in node1_elems:
3195 if not isVolumeFound:
3196 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3197 nb_nodes = self.GetElemNbNodes(node1_elem)
3198 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3199 volume_elem = node1_elem
3200 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3201 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3202 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3203 isVolumeFound = True
3204 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3205 self.SplitQuad([face_id], False) # diagonal 2-4
3206 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3207 isVolumeFound = True
3208 self.SplitQuad([face_id], True) # diagonal 1-3
3209 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3210 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3211 isVolumeFound = True
3212 self.SplitQuad([face_id], True) # diagonal 1-3
3214 ## @brief Splits hexahedrons into tetrahedrons.
3216 # This operation uses pattern mapping functionality for splitting.
3217 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3218 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3219 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3220 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3221 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3222 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3223 # @return TRUE in case of success, FALSE otherwise.
3224 # @ingroup l1_auxiliary
3225 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3226 # Pattern: 5.---------.6
3231 # (0,0,1) 4.---------.7 * |
3238 # (0,0,0) 0.---------.3
3239 pattern_tetra = "!!! Nb of points: \n 8 \n\
3249 !!! Indices of points of 6 tetras: \n\
3257 pattern = self.smeshpyD.GetPattern()
3258 isDone = pattern.LoadFromFile(pattern_tetra)
3260 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3263 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3264 isDone = pattern.MakeMesh(self.mesh, False, False)
3265 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3267 # split quafrangle faces near triangular facets of volumes
3268 self.SplitQuadsNearTriangularFacets()
3272 ## @brief Split hexahedrons into prisms.
3274 # Uses the pattern mapping functionality for splitting.
3275 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3276 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3277 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3278 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3279 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3280 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3281 # @return TRUE in case of success, FALSE otherwise.
3282 # @ingroup l1_auxiliary
3283 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3284 # Pattern: 5.---------.6
3289 # (0,0,1) 4.---------.7 |
3296 # (0,0,0) 0.---------.3
3297 pattern_prism = "!!! Nb of points: \n 8 \n\
3307 !!! Indices of points of 2 prisms: \n\
3311 pattern = self.smeshpyD.GetPattern()
3312 isDone = pattern.LoadFromFile(pattern_prism)
3314 print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3317 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3318 isDone = pattern.MakeMesh(self.mesh, False, False)
3319 if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3321 # Splits quafrangle faces near triangular facets of volumes
3322 self.SplitQuadsNearTriangularFacets()
3326 ## Smoothes elements
3327 # @param IDsOfElements the list if ids of elements to smooth
3328 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3329 # Note that nodes built on edges and boundary nodes are always fixed.
3330 # @param MaxNbOfIterations the maximum number of iterations
3331 # @param MaxAspectRatio varies in range [1.0, inf]
3332 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3333 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3334 # @return TRUE in case of success, FALSE otherwise.
3335 # @ingroup l2_modif_smooth
3336 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3337 MaxNbOfIterations, MaxAspectRatio, Method):
3338 if IDsOfElements == []:
3339 IDsOfElements = self.GetElementsId()
3340 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3341 self.mesh.SetParameters(Parameters)
3342 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3343 MaxNbOfIterations, MaxAspectRatio, Method)
3345 ## Smoothes elements which belong to the given object
3346 # @param theObject the object to smooth
3347 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3348 # Note that nodes built on edges and boundary nodes are always fixed.
3349 # @param MaxNbOfIterations the maximum number of iterations
3350 # @param MaxAspectRatio varies in range [1.0, inf]
3351 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3352 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3353 # @return TRUE in case of success, FALSE otherwise.
3354 # @ingroup l2_modif_smooth
3355 def SmoothObject(self, theObject, IDsOfFixedNodes,
3356 MaxNbOfIterations, MaxAspectRatio, Method):
3357 if ( isinstance( theObject, Mesh )):
3358 theObject = theObject.GetMesh()
3359 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3360 MaxNbOfIterations, MaxAspectRatio, Method)
3362 ## Parametrically smoothes the given elements
3363 # @param IDsOfElements the list if ids of elements to smooth
3364 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3365 # Note that nodes built on edges and boundary nodes are always fixed.
3366 # @param MaxNbOfIterations the maximum number of iterations
3367 # @param MaxAspectRatio varies in range [1.0, inf]
3368 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3369 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3370 # @return TRUE in case of success, FALSE otherwise.
3371 # @ingroup l2_modif_smooth
3372 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3373 MaxNbOfIterations, MaxAspectRatio, Method):
3374 if IDsOfElements == []:
3375 IDsOfElements = self.GetElementsId()
3376 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3377 self.mesh.SetParameters(Parameters)
3378 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3379 MaxNbOfIterations, MaxAspectRatio, Method)
3381 ## Parametrically smoothes the elements which belong to the given object
3382 # @param theObject the object to smooth
3383 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3384 # Note that nodes built on edges and boundary nodes are always fixed.
3385 # @param MaxNbOfIterations the maximum number of iterations
3386 # @param MaxAspectRatio varies in range [1.0, inf]
3387 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3388 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3389 # @return TRUE in case of success, FALSE otherwise.
3390 # @ingroup l2_modif_smooth
3391 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3392 MaxNbOfIterations, MaxAspectRatio, Method):
3393 if ( isinstance( theObject, Mesh )):
3394 theObject = theObject.GetMesh()
3395 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3396 MaxNbOfIterations, MaxAspectRatio, Method)
3398 ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3399 # them with quadratic with the same id.
3400 # @param theForce3d new node creation method:
3401 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3402 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3403 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3404 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3405 # @ingroup l2_modif_tofromqu
3406 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3407 if isinstance( theSubMesh, Mesh ):
3408 theSubMesh = theSubMesh.mesh
3410 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3413 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3415 self.editor.ConvertToQuadratic(theForce3d)
3416 error = self.editor.GetLastError()
3417 if error and error.comment:
3420 ## Converts the mesh from quadratic to ordinary,
3421 # deletes old quadratic elements, \n replacing
3422 # them with ordinary mesh elements with the same id.
3423 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3424 # @ingroup l2_modif_tofromqu
3425 def ConvertFromQuadratic(self, theSubMesh=None):
3427 self.editor.ConvertFromQuadraticObject(theSubMesh)
3429 return self.editor.ConvertFromQuadratic()
3431 ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3432 # @return TRUE if operation has been completed successfully, FALSE otherwise
3433 # @ingroup l2_modif_edit
3434 def Make2DMeshFrom3D(self):
3435 return self.editor. Make2DMeshFrom3D()
3437 ## Creates missing boundary elements
3438 # @param elements - elements whose boundary is to be checked:
3439 # mesh, group, sub-mesh or list of elements
3440 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3441 # @param dimension - defines type of boundary elements to create:
3442 # SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3443 # SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3444 # @param groupName - a name of group to store created boundary elements in,
3445 # "" means not to create the group
3446 # @param meshName - a name of new mesh to store created boundary elements in,
3447 # "" means not to create the new mesh
3448 # @param toCopyElements - if true, the checked elements will be copied into
3449 # the new mesh else only boundary elements will be copied into the new mesh
3450 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3451 # boundary elements will be copied into the new mesh
3452 # @return tuple (mesh, group) where boundary elements were added to
3453 # @ingroup l2_modif_edit
3454 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3455 toCopyElements=False, toCopyExistingBondary=False):
3456 unRegister = genObjUnRegister()
3457 if isinstance( elements, Mesh ):
3458 elements = elements.GetMesh()
3459 if ( isinstance( elements, list )):
3460 elemType = SMESH.ALL
3461 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3462 elements = self.editor.MakeIDSource(elements, elemType)
3463 unRegister.set( elements )
3464 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3465 toCopyElements,toCopyExistingBondary)
3466 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3470 # @brief Creates missing boundary elements around either the whole mesh or
3471 # groups of elements
3472 # @param dimension - defines type of boundary elements to create
3473 # @param groupName - a name of group to store all boundary elements in,
3474 # "" means not to create the group
3475 # @param meshName - a name of a new mesh, which is a copy of the initial
3476 # mesh + created boundary elements; "" means not to create the new mesh
3477 # @param toCopyAll - if true, the whole initial mesh will be copied into
3478 # the new mesh else only boundary elements will be copied into the new mesh
3479 # @param groups - groups of elements to make boundary around
3480 # @retval tuple( long, mesh, groups )
3481 # long - number of added boundary elements
3482 # mesh - the mesh where elements were added to
3483 # group - the group of boundary elements or None
3485 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3486 toCopyAll=False, groups=[]):
3487 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3489 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3490 return nb, mesh, group
3492 ## Renumber mesh nodes (Obsolete, does nothing)
3493 # @ingroup l2_modif_renumber
3494 def RenumberNodes(self):
3495 self.editor.RenumberNodes()
3497 ## Renumber mesh elements (Obsole, does nothing)
3498 # @ingroup l2_modif_renumber
3499 def RenumberElements(self):
3500 self.editor.RenumberElements()
3502 ## Generates new elements by rotation of the elements around the axis
3503 # @param IDsOfElements the list of ids of elements to sweep
3504 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3505 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3506 # @param NbOfSteps the number of steps
3507 # @param Tolerance tolerance
3508 # @param MakeGroups forces the generation of new groups from existing ones
3509 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3510 # of all steps, else - size of each step
3511 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3512 # @ingroup l2_modif_extrurev
3513 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3514 MakeGroups=False, TotalAngle=False):
3515 if IDsOfElements == []:
3516 IDsOfElements = self.GetElementsId()
3517 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3518 Axis = self.smeshpyD.GetAxisStruct(Axis)
3519 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3520 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3521 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3522 self.mesh.SetParameters(Parameters)
3523 if TotalAngle and NbOfSteps:
3524 AngleInRadians /= NbOfSteps
3526 return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3527 AngleInRadians, NbOfSteps, Tolerance)
3528 self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3531 ## Generates new elements by rotation of the elements of object around the axis
3532 # @param theObject object which elements should be sweeped.
3533 # It can be a mesh, a sub mesh or a group.
3534 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3535 # @param AngleInRadians the angle of Rotation
3536 # @param NbOfSteps number of steps
3537 # @param Tolerance tolerance
3538 # @param MakeGroups forces the generation of new groups from existing ones
3539 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3540 # of all steps, else - size of each step
3541 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3542 # @ingroup l2_modif_extrurev
3543 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3544 MakeGroups=False, TotalAngle=False):
3545 if ( isinstance( theObject, Mesh )):
3546 theObject = theObject.GetMesh()
3547 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3548 Axis = self.smeshpyD.GetAxisStruct(Axis)
3549 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3550 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3551 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3552 self.mesh.SetParameters(Parameters)
3553 if TotalAngle and NbOfSteps:
3554 AngleInRadians /= NbOfSteps
3556 return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3557 NbOfSteps, Tolerance)
3558 self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3561 ## Generates new elements by rotation of the elements of object around the axis
3562 # @param theObject object which elements should be sweeped.
3563 # It can be a mesh, a sub mesh or a group.
3564 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3565 # @param AngleInRadians the angle of Rotation
3566 # @param NbOfSteps number of steps
3567 # @param Tolerance tolerance
3568 # @param MakeGroups forces the generation of new groups from existing ones
3569 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3570 # of all steps, else - size of each step
3571 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3572 # @ingroup l2_modif_extrurev
3573 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3574 MakeGroups=False, TotalAngle=False):
3575 if ( isinstance( theObject, Mesh )):
3576 theObject = theObject.GetMesh()
3577 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3578 Axis = self.smeshpyD.GetAxisStruct(Axis)
3579 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3580 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3581 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3582 self.mesh.SetParameters(Parameters)
3583 if TotalAngle and NbOfSteps:
3584 AngleInRadians /= NbOfSteps
3586 return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3587 NbOfSteps, Tolerance)
3588 self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
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 RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3604 MakeGroups=False, TotalAngle=False):
3605 if ( isinstance( theObject, Mesh )):
3606 theObject = theObject.GetMesh()
3607 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3608 Axis = self.smeshpyD.GetAxisStruct(Axis)
3609 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3610 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3611 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3612 self.mesh.SetParameters(Parameters)
3613 if TotalAngle and NbOfSteps:
3614 AngleInRadians /= NbOfSteps
3616 return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3617 NbOfSteps, Tolerance)
3618 self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3621 ## Generates new elements by extrusion of the elements with given ids
3622 # @param IDsOfElements the list of elements ids for extrusion
3623 # @param StepVector vector or DirStruct or 3 vector components, defining
3624 # the direction and value of extrusion for one step (the total extrusion
3625 # length will be NbOfSteps * ||StepVector||)
3626 # @param NbOfSteps the number of steps
3627 # @param MakeGroups forces the generation of new groups from existing ones
3628 # @param IsNodes is True if elements with given ids are nodes
3629 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3630 # @ingroup l2_modif_extrurev
3631 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3632 if IDsOfElements == []:
3633 IDsOfElements = self.GetElementsId()
3634 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3635 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3636 if isinstance( StepVector, list ):
3637 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3638 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3639 Parameters = StepVector.PS.parameters + var_separator + Parameters
3640 self.mesh.SetParameters(Parameters)
3643 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3645 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3647 self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3649 self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3652 ## Generates new elements by extrusion of the elements with given ids
3653 # @param IDsOfElements is ids of elements
3654 # @param StepVector vector or DirStruct or 3 vector components, defining
3655 # the direction and value of extrusion for one step (the total extrusion
3656 # length will be NbOfSteps * ||StepVector||)
3657 # @param NbOfSteps the number of steps
3658 # @param ExtrFlags sets flags for extrusion
3659 # @param SewTolerance uses for comparing locations of nodes if flag
3660 # EXTRUSION_FLAG_SEW is set
3661 # @param MakeGroups forces the generation of new groups from existing ones
3662 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3663 # @ingroup l2_modif_extrurev
3664 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3665 ExtrFlags, SewTolerance, MakeGroups=False):
3666 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3667 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3668 if isinstance( StepVector, list ):
3669 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3671 return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3672 ExtrFlags, SewTolerance)
3673 self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3674 ExtrFlags, SewTolerance)
3677 ## Generates new elements by extrusion along the normal to a discretized surface or wire
3678 # @param Elements container of elements to extrude;
3679 # it can be Mesh, Group, Sub-mesh, Filter or list of IDs;
3680 # Only faces can be extruded so far. Sub-mesh sould be a sub-mesh on geom faces.
3681 # @param StepSize length of one extrusion step (the total extrusion
3682 # length will be \a NbOfSteps * \a StepSize ).
3683 # @param NbOfSteps number of extrusion steps.
3684 # @param ByAverageNormal if True each node is translated by \a StepSize
3685 # along the average of the normal vectors to the faces sharing the node;
3686 # else each node is translated along the same average normal till
3687 # intersection with the plane got by translation of the face sharing
3688 # the node along its own normal by \a StepSize.
3689 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3690 # for every node of \a Elements.
3691 # @param MakeGroups forces generation of new groups from existing ones.
3692 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3693 # is not yet implemented. This parameter is used if \a Elements contains
3694 # both faces and edges, i.e. \a Elements is a Mesh.
3695 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3696 # empty list otherwise.
3697 # @ingroup l2_modif_extrurev
3698 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3699 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3700 unRegister = genObjUnRegister()
3701 if isinstance( Elements, Mesh ):
3702 Elements = Elements.GetMesh()
3703 if isinstance( Elements, list ):
3705 raise RuntimeError, "List of element IDs is empty!"
3706 if not isinstance( Elements[0], int ):
3707 raise RuntimeError, "List must contain element IDs and not %s"% Elements[0]
3708 Elements = self.GetIDSource( Elements, SMESH.ALL )
3709 unRegister.set( Elements )
3710 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3711 self.mesh.SetParameters(Parameters)
3712 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3713 UseInputElemsOnly, ByAverageNormal, MakeGroups, Dim)
3715 ## Generates new elements by extrusion of the elements which belong to the object
3716 # @param theObject the object which elements should be processed.
3717 # It can be a mesh, a sub mesh or a group.
3718 # @param StepVector vector or DirStruct or 3 vector components, defining
3719 # the direction and value of extrusion for one step (the total extrusion
3720 # length will be NbOfSteps * ||StepVector||)
3721 # @param NbOfSteps the number of steps
3722 # @param MakeGroups forces the generation of new groups from existing ones
3723 # @param IsNodes is True if elements which belong to the object are nodes
3724 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3725 # @ingroup l2_modif_extrurev
3726 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3727 if ( isinstance( theObject, Mesh )):
3728 theObject = theObject.GetMesh()
3729 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3730 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3731 if isinstance( StepVector, list ):
3732 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3733 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3734 Parameters = StepVector.PS.parameters + var_separator + Parameters
3735 self.mesh.SetParameters(Parameters)
3738 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3740 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3742 self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3744 self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3747 ## Generates new elements by extrusion of the elements which belong to the object
3748 # @param theObject object which elements should be processed.
3749 # It can be a mesh, a sub mesh or a group.
3750 # @param StepVector vector or DirStruct or 3 vector components, defining
3751 # the direction and value of extrusion for one step (the total extrusion
3752 # length will be NbOfSteps * ||StepVector||)
3753 # @param NbOfSteps the number of steps
3754 # @param MakeGroups to generate new groups from existing ones
3755 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3756 # @ingroup l2_modif_extrurev
3757 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3758 if ( isinstance( theObject, Mesh )):
3759 theObject = theObject.GetMesh()
3760 if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3761 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3762 if isinstance( StepVector, list ):
3763 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3764 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3765 Parameters = StepVector.PS.parameters + var_separator + Parameters
3766 self.mesh.SetParameters(Parameters)
3768 return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3769 self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3772 ## Generates new elements by extrusion of the elements which belong to the object
3773 # @param theObject object which elements should be processed.
3774 # It can be a mesh, a sub mesh or a group.
3775 # @param StepVector vector or DirStruct or 3 vector components, defining
3776 # the direction and value of extrusion for one step (the total extrusion
3777 # length will be NbOfSteps * ||StepVector||)
3778 # @param NbOfSteps the number of steps
3779 # @param MakeGroups forces the generation of new groups from existing ones
3780 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3781 # @ingroup l2_modif_extrurev
3782 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3783 if ( isinstance( theObject, Mesh )):
3784 theObject = theObject.GetMesh()
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 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3790 Parameters = StepVector.PS.parameters + var_separator + Parameters
3791 self.mesh.SetParameters(Parameters)
3793 return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3794 self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3799 ## Generates new elements by extrusion of the given elements
3800 # The path of extrusion must be a meshed edge.
3801 # @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3802 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3803 # @param NodeStart the start node from Path. Defines the direction of extrusion
3804 # @param HasAngles allows the shape to be rotated around the path
3805 # to get the resulting mesh in a helical fashion
3806 # @param Angles list of angles in radians
3807 # @param LinearVariation forces the computation of rotation angles as linear
3808 # variation of the given Angles along path steps
3809 # @param HasRefPoint allows using the reference point
3810 # @param RefPoint the point around which the elements are rotated (the mass
3811 # center of the elements by default).
3812 # The User can specify any point as the Reference Point.
3813 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
3814 # @param MakeGroups forces the generation of new groups from existing ones
3815 # @param ElemType type of elements for extrusion (if param Base is a mesh)
3816 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3817 # only SMESH::Extrusion_Error otherwise
3818 # @ingroup l2_modif_extrurev
3819 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3820 HasAngles, Angles, LinearVariation,
3821 HasRefPoint, RefPoint, MakeGroups, ElemType):
3822 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3823 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3825 elif isinstance( RefPoint, list ):
3826 RefPoint = PointStruct(*RefPoint)
3828 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3829 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3830 self.mesh.SetParameters(Parameters)
3832 if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3834 if isinstance(Base, list):
3836 if Base == []: IDsOfElements = self.GetElementsId()
3837 else: IDsOfElements = Base
3838 return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3839 HasAngles, Angles, LinearVariation,
3840 HasRefPoint, RefPoint, MakeGroups, ElemType)
3842 if isinstance(Base, Mesh): Base = Base.GetMesh()
3843 if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3844 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3845 HasAngles, Angles, LinearVariation,
3846 HasRefPoint, RefPoint, MakeGroups, ElemType)
3848 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3851 ## Generates new elements by extrusion of the given elements
3852 # The path of extrusion must be a meshed edge.
3853 # @param IDsOfElements ids of elements
3854 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3855 # @param PathShape shape(edge) defines the sub-mesh for the path
3856 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3857 # @param HasAngles allows the shape to be rotated around the path
3858 # to get the resulting mesh in a helical fashion
3859 # @param Angles list of angles in radians
3860 # @param HasRefPoint allows using the reference point
3861 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3862 # The User can specify any point as the Reference Point.
3863 # @param MakeGroups forces the generation of new groups from existing ones
3864 # @param LinearVariation forces the computation of rotation angles as linear
3865 # variation of the given Angles along path steps
3866 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3867 # only SMESH::Extrusion_Error otherwise
3868 # @ingroup l2_modif_extrurev
3869 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3870 HasAngles, Angles, HasRefPoint, RefPoint,
3871 MakeGroups=False, LinearVariation=False):
3872 if IDsOfElements == []:
3873 IDsOfElements = self.GetElementsId()
3874 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3875 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3877 if ( isinstance( PathMesh, Mesh )):
3878 PathMesh = PathMesh.GetMesh()
3879 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3880 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3881 self.mesh.SetParameters(Parameters)
3882 if HasAngles and Angles and LinearVariation:
3883 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3886 return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3887 PathShape, NodeStart, HasAngles,
3888 Angles, HasRefPoint, RefPoint)
3889 return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3890 NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3892 ## Generates new elements by extrusion of the elements which belong to the object
3893 # The path of extrusion must be a meshed edge.
3894 # @param theObject the object which elements should be processed.
3895 # It can be a mesh, a sub mesh or a group.
3896 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3897 # @param PathShape shape(edge) defines the sub-mesh for the path
3898 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3899 # @param HasAngles allows the shape to be rotated around the path
3900 # to get the resulting mesh in a helical fashion
3901 # @param Angles list of angles
3902 # @param HasRefPoint allows using the reference point
3903 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3904 # The User can specify any point as the Reference Point.
3905 # @param MakeGroups forces the generation of new groups from existing ones
3906 # @param LinearVariation forces the computation of rotation angles as linear
3907 # variation of the given Angles along path steps
3908 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3909 # only SMESH::Extrusion_Error otherwise
3910 # @ingroup l2_modif_extrurev
3911 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3912 HasAngles, Angles, HasRefPoint, RefPoint,
3913 MakeGroups=False, LinearVariation=False):
3914 if ( isinstance( theObject, Mesh )):
3915 theObject = theObject.GetMesh()
3916 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3917 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3918 if ( isinstance( PathMesh, Mesh )):
3919 PathMesh = PathMesh.GetMesh()
3920 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3921 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3922 self.mesh.SetParameters(Parameters)
3923 if HasAngles and Angles and LinearVariation:
3924 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3927 return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3928 PathShape, NodeStart, HasAngles,
3929 Angles, HasRefPoint, RefPoint)
3930 return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3931 NodeStart, HasAngles, Angles, HasRefPoint,
3934 ## Generates new elements by extrusion of the elements which belong to the object
3935 # The path of extrusion must be a meshed edge.
3936 # @param theObject the object which elements should be processed.
3937 # It can be a mesh, a sub mesh or a group.
3938 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3939 # @param PathShape shape(edge) defines the sub-mesh for the path
3940 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3941 # @param HasAngles allows the shape to be rotated around the path
3942 # to get the resulting mesh in a helical fashion
3943 # @param Angles list of angles
3944 # @param HasRefPoint allows using the reference point
3945 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3946 # The User can specify any point as the Reference Point.
3947 # @param MakeGroups forces the generation of new groups from existing ones
3948 # @param LinearVariation forces the computation of rotation angles as linear
3949 # variation of the given Angles along path steps
3950 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3951 # only SMESH::Extrusion_Error otherwise
3952 # @ingroup l2_modif_extrurev
3953 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3954 HasAngles, Angles, HasRefPoint, RefPoint,
3955 MakeGroups=False, LinearVariation=False):
3956 if ( isinstance( theObject, Mesh )):
3957 theObject = theObject.GetMesh()
3958 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3959 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3960 if ( isinstance( PathMesh, Mesh )):
3961 PathMesh = PathMesh.GetMesh()
3962 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3963 Parameters = AnglesParameters + var_separator + RefPoint.parameters
3964 self.mesh.SetParameters(Parameters)
3965 if HasAngles and Angles and LinearVariation:
3966 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3969 return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3970 PathShape, NodeStart, HasAngles,
3971 Angles, HasRefPoint, RefPoint)
3972 return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3973 NodeStart, HasAngles, Angles, HasRefPoint,
3976 ## Generates new elements by extrusion of the elements which belong to the object
3977 # The path of extrusion must be a meshed edge.
3978 # @param theObject the object which elements should be processed.
3979 # It can be a mesh, a sub mesh or a group.
3980 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3981 # @param PathShape shape(edge) defines the sub-mesh for the path
3982 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3983 # @param HasAngles allows the shape to be rotated around the path
3984 # to get the resulting mesh in a helical fashion
3985 # @param Angles list of angles
3986 # @param HasRefPoint allows using the reference point
3987 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3988 # The User can specify any point as the Reference Point.
3989 # @param MakeGroups forces the generation of new groups from existing ones
3990 # @param LinearVariation forces the computation of rotation angles as linear
3991 # variation of the given Angles along path steps
3992 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3993 # only SMESH::Extrusion_Error otherwise
3994 # @ingroup l2_modif_extrurev
3995 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3996 HasAngles, Angles, HasRefPoint, RefPoint,
3997 MakeGroups=False, LinearVariation=False):
3998 if ( isinstance( theObject, Mesh )):
3999 theObject = theObject.GetMesh()
4000 if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
4001 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4002 if ( isinstance( PathMesh, Mesh )):
4003 PathMesh = PathMesh.GetMesh()
4004 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4005 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4006 self.mesh.SetParameters(Parameters)
4007 if HasAngles and Angles and LinearVariation:
4008 Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
4011 return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
4012 PathShape, NodeStart, HasAngles,
4013 Angles, HasRefPoint, RefPoint)
4014 return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
4015 NodeStart, HasAngles, Angles, HasRefPoint,
4018 ## Creates a symmetrical copy of mesh elements
4019 # @param IDsOfElements list of elements ids
4020 # @param Mirror is AxisStruct or geom object(point, line, plane)
4021 # @param theMirrorType is POINT, AXIS or PLANE
4022 # If the Mirror is a geom object this parameter is unnecessary
4023 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4024 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4025 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4026 # @ingroup l2_modif_trsf
4027 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4028 if IDsOfElements == []:
4029 IDsOfElements = self.GetElementsId()
4030 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4031 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4032 theMirrorType = Mirror._mirrorType
4034 self.mesh.SetParameters(Mirror.parameters)
4035 if Copy and MakeGroups:
4036 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4037 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4040 ## Creates a new mesh by a symmetrical copy of mesh elements
4041 # @param IDsOfElements the list of elements ids
4042 # @param Mirror is AxisStruct or geom object (point, line, plane)
4043 # @param theMirrorType is POINT, AXIS or PLANE
4044 # If the Mirror is a geom object this parameter is unnecessary
4045 # @param MakeGroups to generate new groups from existing ones
4046 # @param NewMeshName a name of the new mesh to create
4047 # @return instance of Mesh class
4048 # @ingroup l2_modif_trsf
4049 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4050 if IDsOfElements == []:
4051 IDsOfElements = self.GetElementsId()
4052 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4053 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4054 theMirrorType = Mirror._mirrorType
4056 self.mesh.SetParameters(Mirror.parameters)
4057 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4058 MakeGroups, NewMeshName)
4059 return Mesh(self.smeshpyD,self.geompyD,mesh)
4061 ## Creates a symmetrical copy of the object
4062 # @param theObject mesh, submesh or group
4063 # @param Mirror AxisStruct or geom object (point, line, plane)
4064 # @param theMirrorType is POINT, AXIS or PLANE
4065 # If the Mirror is a geom object this parameter is unnecessary
4066 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4067 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4068 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4069 # @ingroup l2_modif_trsf
4070 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4071 if ( isinstance( theObject, Mesh )):
4072 theObject = theObject.GetMesh()
4073 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4074 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4075 theMirrorType = Mirror._mirrorType
4077 self.mesh.SetParameters(Mirror.parameters)
4078 if Copy and MakeGroups:
4079 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4080 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4083 ## Creates a new mesh by a symmetrical copy of the object
4084 # @param theObject mesh, submesh or group
4085 # @param Mirror AxisStruct or geom object (point, line, plane)
4086 # @param theMirrorType POINT, AXIS or PLANE
4087 # If the Mirror is a geom object this parameter is unnecessary
4088 # @param MakeGroups forces the generation of new groups from existing ones
4089 # @param NewMeshName the name of the new mesh to create
4090 # @return instance of Mesh class
4091 # @ingroup l2_modif_trsf
4092 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4093 if ( isinstance( theObject, Mesh )):
4094 theObject = theObject.GetMesh()
4095 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4096 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4097 theMirrorType = Mirror._mirrorType
4099 self.mesh.SetParameters(Mirror.parameters)
4100 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4101 MakeGroups, NewMeshName)
4102 return Mesh( self.smeshpyD,self.geompyD,mesh )
4104 ## Translates the elements
4105 # @param IDsOfElements list of elements ids
4106 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4107 # @param Copy allows copying the translated elements
4108 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4109 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4110 # @ingroup l2_modif_trsf
4111 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4112 if IDsOfElements == []:
4113 IDsOfElements = self.GetElementsId()
4114 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4115 Vector = self.smeshpyD.GetDirStruct(Vector)
4116 if isinstance( Vector, list ):
4117 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4118 self.mesh.SetParameters(Vector.PS.parameters)
4119 if Copy and MakeGroups:
4120 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4121 self.editor.Translate(IDsOfElements, Vector, Copy)
4124 ## Creates a new mesh of translated elements
4125 # @param IDsOfElements list of elements ids
4126 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4127 # @param MakeGroups forces the generation of new groups from existing ones
4128 # @param NewMeshName the name of the newly created mesh
4129 # @return instance of Mesh class
4130 # @ingroup l2_modif_trsf
4131 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4132 if IDsOfElements == []:
4133 IDsOfElements = self.GetElementsId()
4134 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4135 Vector = self.smeshpyD.GetDirStruct(Vector)
4136 if isinstance( Vector, list ):
4137 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4138 self.mesh.SetParameters(Vector.PS.parameters)
4139 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4140 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4142 ## Translates the object
4143 # @param theObject the object to translate (mesh, submesh, or group)
4144 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4145 # @param Copy allows copying the translated elements
4146 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4147 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4148 # @ingroup l2_modif_trsf
4149 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4150 if ( isinstance( theObject, Mesh )):
4151 theObject = theObject.GetMesh()
4152 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4153 Vector = self.smeshpyD.GetDirStruct(Vector)
4154 if isinstance( Vector, list ):
4155 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4156 self.mesh.SetParameters(Vector.PS.parameters)
4157 if Copy and MakeGroups:
4158 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4159 self.editor.TranslateObject(theObject, Vector, Copy)
4162 ## Creates a new mesh from the translated object
4163 # @param theObject the object to translate (mesh, submesh, or group)
4164 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4165 # @param MakeGroups forces the generation of new groups from existing ones
4166 # @param NewMeshName the name of the newly created mesh
4167 # @return instance of Mesh class
4168 # @ingroup l2_modif_trsf
4169 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4170 if isinstance( theObject, Mesh ):
4171 theObject = theObject.GetMesh()
4172 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4173 Vector = self.smeshpyD.GetDirStruct(Vector)
4174 if isinstance( Vector, list ):
4175 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4176 self.mesh.SetParameters(Vector.PS.parameters)
4177 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4178 return Mesh( self.smeshpyD, self.geompyD, mesh )
4182 ## Scales the object
4183 # @param theObject - the object to translate (mesh, submesh, or group)
4184 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4185 # @param theScaleFact - list of 1-3 scale factors for axises
4186 # @param Copy - allows copying the translated elements
4187 # @param MakeGroups - forces the generation of new groups from existing
4189 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4190 # empty list otherwise
4191 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4192 unRegister = genObjUnRegister()
4193 if ( isinstance( theObject, Mesh )):
4194 theObject = theObject.GetMesh()
4195 if ( isinstance( theObject, list )):
4196 theObject = self.GetIDSource(theObject, SMESH.ALL)
4197 unRegister.set( theObject )
4198 if ( isinstance( thePoint, list )):
4199 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4200 if ( isinstance( theScaleFact, float )):
4201 theScaleFact = [theScaleFact]
4202 if ( isinstance( theScaleFact, int )):
4203 theScaleFact = [ float(theScaleFact)]
4205 self.mesh.SetParameters(thePoint.parameters)
4207 if Copy and MakeGroups:
4208 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4209 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4212 ## Creates a new mesh from the translated object
4213 # @param theObject - the object to translate (mesh, submesh, or group)
4214 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4215 # @param theScaleFact - list of 1-3 scale factors for axises
4216 # @param MakeGroups - forces the generation of new groups from existing ones
4217 # @param NewMeshName - the name of the newly created mesh
4218 # @return instance of Mesh class
4219 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4220 unRegister = genObjUnRegister()
4221 if (isinstance(theObject, Mesh)):
4222 theObject = theObject.GetMesh()
4223 if ( isinstance( theObject, list )):
4224 theObject = self.GetIDSource(theObject,SMESH.ALL)
4225 unRegister.set( theObject )
4226 if ( isinstance( thePoint, list )):
4227 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4228 if ( isinstance( theScaleFact, float )):
4229 theScaleFact = [theScaleFact]
4230 if ( isinstance( theScaleFact, int )):
4231 theScaleFact = [ float(theScaleFact)]
4233 self.mesh.SetParameters(thePoint.parameters)
4234 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4235 MakeGroups, NewMeshName)
4236 return Mesh( self.smeshpyD, self.geompyD, mesh )
4240 ## Rotates the elements
4241 # @param IDsOfElements list of elements ids
4242 # @param Axis the axis of rotation (AxisStruct or geom line)
4243 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4244 # @param Copy allows copying the rotated elements
4245 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4246 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4247 # @ingroup l2_modif_trsf
4248 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4249 if IDsOfElements == []:
4250 IDsOfElements = self.GetElementsId()
4251 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4252 Axis = self.smeshpyD.GetAxisStruct(Axis)
4253 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4254 Parameters = Axis.parameters + var_separator + Parameters
4255 self.mesh.SetParameters(Parameters)
4256 if Copy and MakeGroups:
4257 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4258 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4261 ## Creates a new mesh of rotated elements
4262 # @param IDsOfElements list of element ids
4263 # @param Axis the axis of rotation (AxisStruct or geom line)
4264 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4265 # @param MakeGroups forces the generation of new groups from existing ones
4266 # @param NewMeshName the name of the newly created mesh
4267 # @return instance of Mesh class
4268 # @ingroup l2_modif_trsf
4269 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4270 if IDsOfElements == []:
4271 IDsOfElements = self.GetElementsId()
4272 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4273 Axis = self.smeshpyD.GetAxisStruct(Axis)
4274 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4275 Parameters = Axis.parameters + var_separator + Parameters
4276 self.mesh.SetParameters(Parameters)
4277 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4278 MakeGroups, NewMeshName)
4279 return Mesh( self.smeshpyD, self.geompyD, mesh )
4281 ## Rotates the object
4282 # @param theObject the object to rotate( mesh, submesh, or group)
4283 # @param Axis the axis of rotation (AxisStruct or geom line)
4284 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4285 # @param Copy allows copying the rotated elements
4286 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4287 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4288 # @ingroup l2_modif_trsf
4289 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4290 if (isinstance(theObject, Mesh)):
4291 theObject = theObject.GetMesh()
4292 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4293 Axis = self.smeshpyD.GetAxisStruct(Axis)
4294 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4295 Parameters = Axis.parameters + ":" + Parameters
4296 self.mesh.SetParameters(Parameters)
4297 if Copy and MakeGroups:
4298 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4299 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4302 ## Creates a new mesh from the rotated object
4303 # @param theObject the object to rotate (mesh, submesh, or group)
4304 # @param Axis the axis of rotation (AxisStruct or geom line)
4305 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4306 # @param MakeGroups forces the generation of new groups from existing ones
4307 # @param NewMeshName the name of the newly created mesh
4308 # @return instance of Mesh class
4309 # @ingroup l2_modif_trsf
4310 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4311 if (isinstance( theObject, Mesh )):
4312 theObject = theObject.GetMesh()
4313 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4314 Axis = self.smeshpyD.GetAxisStruct(Axis)
4315 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4316 Parameters = Axis.parameters + ":" + Parameters
4317 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4318 MakeGroups, NewMeshName)
4319 self.mesh.SetParameters(Parameters)
4320 return Mesh( self.smeshpyD, self.geompyD, mesh )
4322 ## Finds groups of adjacent nodes within Tolerance.
4323 # @param Tolerance the value of tolerance
4324 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4325 # @ingroup l2_modif_trsf
4326 def FindCoincidentNodes (self, Tolerance):
4327 return self.editor.FindCoincidentNodes(Tolerance)
4329 ## Finds groups of ajacent nodes within Tolerance.
4330 # @param Tolerance the value of tolerance
4331 # @param SubMeshOrGroup SubMesh or Group
4332 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4333 # @return the list of pairs of nodes IDs (e.g. [[1,12],[25,4]])
4334 # @ingroup l2_modif_trsf
4335 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
4336 unRegister = genObjUnRegister()
4337 if (isinstance( SubMeshOrGroup, Mesh )):
4338 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4339 if not isinstance( exceptNodes, list):
4340 exceptNodes = [ exceptNodes ]
4341 if exceptNodes and isinstance( exceptNodes[0], int):
4342 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
4343 unRegister.set( exceptNodes )
4344 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
4347 # @param GroupsOfNodes a list of pairs of nodes IDs for merging (e.g. [[1,12],[25,4]])
4348 # @ingroup l2_modif_trsf
4349 def MergeNodes (self, GroupsOfNodes):
4350 self.editor.MergeNodes(GroupsOfNodes)
4352 ## Finds the elements built on the same nodes.
4353 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4354 # @return the list of pairs of equal elements IDs (e.g. [[1,12],[25,4]])
4355 # @ingroup l2_modif_trsf
4356 def FindEqualElements (self, MeshOrSubMeshOrGroup):
4357 if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4358 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4359 return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4361 ## Merges elements in each given group.
4362 # @param GroupsOfElementsID a list of pairs of elements IDs for merging (e.g. [[1,12],[25,4]])
4363 # @ingroup l2_modif_trsf
4364 def MergeElements(self, GroupsOfElementsID):
4365 self.editor.MergeElements(GroupsOfElementsID)
4367 ## Leaves one element and removes all other elements built on the same nodes.
4368 # @ingroup l2_modif_trsf
4369 def MergeEqualElements(self):
4370 self.editor.MergeEqualElements()
4372 ## Sews free borders
4373 # @return SMESH::Sew_Error
4374 # @ingroup l2_modif_trsf
4375 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4376 FirstNodeID2, SecondNodeID2, LastNodeID2,
4377 CreatePolygons, CreatePolyedrs):
4378 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4379 FirstNodeID2, SecondNodeID2, LastNodeID2,
4380 CreatePolygons, CreatePolyedrs)
4382 ## Sews conform free borders
4383 # @return SMESH::Sew_Error
4384 # @ingroup l2_modif_trsf
4385 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4386 FirstNodeID2, SecondNodeID2):
4387 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4388 FirstNodeID2, SecondNodeID2)
4390 ## Sews border to side
4391 # @return SMESH::Sew_Error
4392 # @ingroup l2_modif_trsf
4393 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4394 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4395 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4396 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4398 ## Sews two sides of a mesh. The nodes belonging to Side1 are
4399 # merged with the nodes of elements of Side2.
4400 # The number of elements in theSide1 and in theSide2 must be
4401 # equal and they should have similar nodal connectivity.
4402 # The nodes to merge should belong to side borders and
4403 # the first node should be linked to the second.
4404 # @return SMESH::Sew_Error
4405 # @ingroup l2_modif_trsf
4406 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4407 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4408 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4409 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4410 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4411 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4413 ## Sets new nodes for the given element.
4414 # @param ide the element id
4415 # @param newIDs nodes ids
4416 # @return If the number of nodes does not correspond to the type of element - returns false
4417 # @ingroup l2_modif_edit
4418 def ChangeElemNodes(self, ide, newIDs):
4419 return self.editor.ChangeElemNodes(ide, newIDs)
4421 ## If during the last operation of MeshEditor some nodes were
4422 # created, this method returns the list of their IDs, \n
4423 # if new nodes were not created - returns empty list
4424 # @return the list of integer values (can be empty)
4425 # @ingroup l1_auxiliary
4426 def GetLastCreatedNodes(self):
4427 return self.editor.GetLastCreatedNodes()
4429 ## If during the last operation of MeshEditor some elements were
4430 # created this method returns the list of their IDs, \n
4431 # if new elements were not created - returns empty list
4432 # @return the list of integer values (can be empty)
4433 # @ingroup l1_auxiliary
4434 def GetLastCreatedElems(self):
4435 return self.editor.GetLastCreatedElems()
4437 ## Clears sequences of nodes and elements created by mesh edition oparations
4438 # @ingroup l1_auxiliary
4439 def ClearLastCreated(self):
4440 self.editor.ClearLastCreated()
4442 ## Creates Duplicates given elements, i.e. creates new elements based on the
4443 # same nodes as the given ones.
4444 # @param theElements - container of elements to duplicate. It can be a Mesh,
4445 # sub-mesh, group, filter or a list of element IDs.
4446 # @param theGroupName - a name of group to contain the generated elements.
4447 # If a group with such a name already exists, the new elements
4448 # are added to the existng group, else a new group is created.
4449 # If \a theGroupName is empty, new elements are not added
4451 # @return a group where the new elements are added. None if theGroupName == "".
4452 # @ingroup l2_modif_edit
4453 def DoubleElements(self, theElements, theGroupName=""):
4454 unRegister = genObjUnRegister()
4455 if isinstance( theElements, Mesh ):
4456 theElements = theElements.mesh
4457 elif isinstance( theElements, list ):
4458 theElements = self.GetIDSource( theElements, SMESH.ALL )
4459 unRegister.set( theElements )
4460 return self.editor.DoubleElements(theElements, theGroupName)
4462 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4463 # @param theNodes identifiers of nodes to be doubled
4464 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4465 # nodes. If list of element identifiers is empty then nodes are doubled but
4466 # they not assigned to elements
4467 # @return TRUE if operation has been completed successfully, FALSE otherwise
4468 # @ingroup l2_modif_edit
4469 def DoubleNodes(self, theNodes, theModifiedElems):
4470 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4472 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4473 # This method provided for convenience works as DoubleNodes() described above.
4474 # @param theNodeId identifiers of node to be doubled
4475 # @param theModifiedElems identifiers of elements to be updated
4476 # @return TRUE if operation has been completed successfully, FALSE otherwise
4477 # @ingroup l2_modif_edit
4478 def DoubleNode(self, theNodeId, theModifiedElems):
4479 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4481 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4482 # This method provided for convenience works as DoubleNodes() described above.
4483 # @param theNodes group of nodes to be doubled
4484 # @param theModifiedElems group of elements to be updated.
4485 # @param theMakeGroup forces the generation of a group containing new nodes.
4486 # @return TRUE or a created group if operation has been completed successfully,
4487 # FALSE or None otherwise
4488 # @ingroup l2_modif_edit
4489 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4491 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4492 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4494 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4495 # This method provided for convenience works as DoubleNodes() described above.
4496 # @param theNodes list of groups of nodes to be doubled
4497 # @param theModifiedElems list of groups of elements to be updated.
4498 # @param theMakeGroup forces the generation of a group containing new nodes.
4499 # @return TRUE if operation has been completed successfully, FALSE otherwise
4500 # @ingroup l2_modif_edit
4501 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4503 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4504 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4506 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4507 # @param theElems - the list of elements (edges or faces) to be replicated
4508 # The nodes for duplication could be found from these elements
4509 # @param theNodesNot - list of nodes to NOT replicate
4510 # @param theAffectedElems - the list of elements (cells and edges) to which the
4511 # replicated nodes should be associated to.
4512 # @return TRUE if operation has been completed successfully, FALSE otherwise
4513 # @ingroup l2_modif_edit
4514 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4515 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4517 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4518 # @param theElems - the list of elements (edges or faces) to be replicated
4519 # The nodes for duplication could be found from these elements
4520 # @param theNodesNot - list of nodes to NOT replicate
4521 # @param theShape - shape to detect affected elements (element which geometric center
4522 # located on or inside shape).
4523 # The replicated nodes should be associated to affected elements.
4524 # @return TRUE if operation has been completed successfully, FALSE otherwise
4525 # @ingroup l2_modif_edit
4526 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4527 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4529 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4530 # This method provided for convenience works as DoubleNodes() described above.
4531 # @param theElems - group of of elements (edges or faces) to be replicated
4532 # @param theNodesNot - group of nodes not to replicated
4533 # @param theAffectedElems - group of elements to which the replicated nodes
4534 # should be associated to.
4535 # @param theMakeGroup forces the generation of a group containing new elements.
4536 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4537 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4538 # FALSE or None otherwise
4539 # @ingroup l2_modif_edit
4540 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4541 theMakeGroup=False, theMakeNodeGroup=False):
4542 if theMakeGroup or theMakeNodeGroup:
4543 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4545 theMakeGroup, theMakeNodeGroup)
4546 if theMakeGroup and theMakeNodeGroup:
4549 return twoGroups[ int(theMakeNodeGroup) ]
4550 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4552 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4553 # This method provided for convenience works as DoubleNodes() described above.
4554 # @param theElems - group of of elements (edges or faces) to be replicated
4555 # @param theNodesNot - group of nodes not to replicated
4556 # @param theShape - shape to detect affected elements (element which geometric center
4557 # located on or inside shape).
4558 # The replicated nodes should be associated to affected elements.
4559 # @ingroup l2_modif_edit
4560 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4561 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4563 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4564 # This method provided for convenience works as DoubleNodes() described above.
4565 # @param theElems - list of groups of elements (edges or faces) to be replicated
4566 # @param theNodesNot - list of groups of nodes not to replicated
4567 # @param theAffectedElems - group of elements to which the replicated nodes
4568 # should be associated to.
4569 # @param theMakeGroup forces the generation of a group containing new elements.
4570 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4571 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4572 # FALSE or None otherwise
4573 # @ingroup l2_modif_edit
4574 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4575 theMakeGroup=False, theMakeNodeGroup=False):
4576 if theMakeGroup or theMakeNodeGroup:
4577 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4579 theMakeGroup, theMakeNodeGroup)
4580 if theMakeGroup and theMakeNodeGroup:
4583 return twoGroups[ int(theMakeNodeGroup) ]
4584 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4586 ## Creates a hole in a mesh by doubling the nodes of some particular elements
4587 # This method provided for convenience works as DoubleNodes() described above.
4588 # @param theElems - list of groups of elements (edges or faces) to be replicated
4589 # @param theNodesNot - list of groups of nodes not to replicated
4590 # @param theShape - shape to detect affected elements (element which geometric center
4591 # located on or inside shape).
4592 # The replicated nodes should be associated to affected elements.
4593 # @return TRUE if operation has been completed successfully, FALSE otherwise
4594 # @ingroup l2_modif_edit
4595 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4596 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4598 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4599 # This method is the first step of DoubleNodeElemGroupsInRegion.
4600 # @param theElems - list of groups of elements (edges or faces) to be replicated
4601 # @param theNodesNot - list of groups of nodes not to replicated
4602 # @param theShape - shape to detect affected elements (element which geometric center
4603 # located on or inside shape).
4604 # The replicated nodes should be associated to affected elements.
4605 # @return groups of affected elements
4606 # @ingroup l2_modif_edit
4607 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4608 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4610 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4611 # The list of groups must describe a partition of the mesh volumes.
4612 # The nodes of the internal faces at the boundaries of the groups are doubled.
4613 # In option, the internal faces are replaced by flat elements.
4614 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4615 # @param theDomains - list of groups of volumes
4616 # @param createJointElems - if TRUE, create the elements
4617 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4618 # the boundary between \a theDomains and the rest mesh
4619 # @return TRUE if operation has been completed successfully, FALSE otherwise
4620 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4621 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4623 ## Double nodes on some external faces and create flat elements.
4624 # Flat elements are mainly used by some types of mechanic calculations.
4626 # Each group of the list must be constituted of faces.
4627 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4628 # @param theGroupsOfFaces - list of groups of faces
4629 # @return TRUE if operation has been completed successfully, FALSE otherwise
4630 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4631 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4633 ## identify all the elements around a geom shape, get the faces delimiting the hole
4635 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4636 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4638 def _getFunctor(self, funcType ):
4639 fn = self.functors[ funcType._v ]
4641 fn = self.smeshpyD.GetFunctor(funcType)
4642 fn.SetMesh(self.mesh)
4643 self.functors[ funcType._v ] = fn
4646 def _valueFromFunctor(self, funcType, elemId):
4647 fn = self._getFunctor( funcType )
4648 if fn.GetElementType() == self.GetElementType(elemId, True):
4649 val = fn.GetValue(elemId)
4654 ## Get length of 1D element or sum of lengths of all 1D mesh elements
4655 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4656 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4657 # @ingroup l1_measurements
4658 def GetLength(self, elemId=None):
4661 length = self.smeshpyD.GetLength(self)
4663 length = self._valueFromFunctor(SMESH.FT_Length, elemId)
4666 ## Get area of 2D element or sum of areas of all 2D mesh elements
4667 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4668 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4669 # @ingroup l1_measurements
4670 def GetArea(self, elemId=None):
4673 area = self.smeshpyD.GetArea(self)
4675 area = self._valueFromFunctor(SMESH.FT_Area, elemId)
4678 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4679 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4680 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4681 # @ingroup l1_measurements
4682 def GetVolume(self, elemId=None):
4685 volume = self.smeshpyD.GetVolume(self)
4687 volume = self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4690 ## Get maximum element length.
4691 # @param elemId mesh element ID
4692 # @return element's maximum length value
4693 # @ingroup l1_measurements
4694 def GetMaxElementLength(self, elemId):
4695 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4696 ftype = SMESH.FT_MaxElementLength3D
4698 ftype = SMESH.FT_MaxElementLength2D
4699 return self._valueFromFunctor(ftype, elemId)
4701 ## Get aspect ratio of 2D or 3D element.
4702 # @param elemId mesh element ID
4703 # @return element's aspect ratio value
4704 # @ingroup l1_measurements
4705 def GetAspectRatio(self, elemId):
4706 if self.GetElementType(elemId, True) == SMESH.VOLUME:
4707 ftype = SMESH.FT_AspectRatio3D
4709 ftype = SMESH.FT_AspectRatio
4710 return self._valueFromFunctor(ftype, elemId)
4712 ## Get warping angle of 2D element.
4713 # @param elemId mesh element ID
4714 # @return element's warping angle value
4715 # @ingroup l1_measurements
4716 def GetWarping(self, elemId):
4717 return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4719 ## Get minimum angle of 2D element.
4720 # @param elemId mesh element ID
4721 # @return element's minimum angle value
4722 # @ingroup l1_measurements
4723 def GetMinimumAngle(self, elemId):
4724 return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4726 ## Get taper of 2D element.
4727 # @param elemId mesh element ID
4728 # @return element's taper value
4729 # @ingroup l1_measurements
4730 def GetTaper(self, elemId):
4731 return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4733 ## Get skew of 2D element.
4734 # @param elemId mesh element ID
4735 # @return element's skew value
4736 # @ingroup l1_measurements
4737 def GetSkew(self, elemId):
4738 return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4740 ## Return minimal and maximal value of a given functor.
4741 # @param funType a functor type, an item of SMESH.FunctorType enum
4742 # (one of SMESH.FunctorType._items)
4743 # @param meshPart a part of mesh (group, sub-mesh) to treat
4744 # @return tuple (min,max)
4745 # @ingroup l1_measurements
4746 def GetMinMax(self, funType, meshPart=None):
4747 unRegister = genObjUnRegister()
4748 if isinstance( meshPart, list ):
4749 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4750 unRegister.set( meshPart )
4751 if isinstance( meshPart, Mesh ):
4752 meshPart = meshPart.mesh
4753 fun = self._getFunctor( funType )
4756 hist = fun.GetLocalHistogram( 1, False, meshPart )
4758 hist = fun.GetHistogram( 1, False )
4760 return hist[0].min, hist[0].max
4763 pass # end of Mesh class
4765 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4767 class Pattern(SMESH._objref_SMESH_Pattern):
4769 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4770 decrFun = lambda i: i-1
4771 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4772 theMesh.SetParameters(Parameters)
4773 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4775 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4776 decrFun = lambda i: i-1
4777 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4778 theMesh.SetParameters(Parameters)
4779 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4781 # Registering the new proxy for Pattern
4782 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4784 ## Private class used to bind methods creating algorithms to the class Mesh
4789 self.defaultAlgoType = ""
4790 self.algoTypeToClass = {}
4792 # Stores a python class of algorithm
4793 def add(self, algoClass):
4794 if type( algoClass ).__name__ == 'classobj' and \
4795 hasattr( algoClass, "algoType"):
4796 self.algoTypeToClass[ algoClass.algoType ] = algoClass
4797 if not self.defaultAlgoType and \
4798 hasattr( algoClass, "isDefault") and algoClass.isDefault:
4799 self.defaultAlgoType = algoClass.algoType
4800 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4802 # creates a copy of self and assign mesh to the copy
4803 def copy(self, mesh):
4804 other = algoCreator()
4805 other.defaultAlgoType = self.defaultAlgoType
4806 other.algoTypeToClass = self.algoTypeToClass
4810 # creates an instance of algorithm
4811 def __call__(self,algo="",geom=0,*args):
4812 algoType = self.defaultAlgoType
4813 for arg in args + (algo,geom):
4814 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4816 if isinstance( arg, str ) and arg:
4818 if not algoType and self.algoTypeToClass:
4819 algoType = self.algoTypeToClass.keys()[0]
4820 if self.algoTypeToClass.has_key( algoType ):
4821 #print "Create algo",algoType
4822 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4823 raise RuntimeError, "No class found for algo type %s" % algoType
4826 # Private class used to substitute and store variable parameters of hypotheses.
4828 class hypMethodWrapper:
4829 def __init__(self, hyp, method):
4831 self.method = method
4832 #print "REBIND:", method.__name__
4835 # call a method of hypothesis with calling SetVarParameter() before
4836 def __call__(self,*args):
4838 return self.method( self.hyp, *args ) # hypothesis method with no args
4840 #print "MethWrapper.__call__",self.method.__name__, args
4842 parsed = ParseParameters(*args) # replace variables with their values
4843 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4844 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4845 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4846 # maybe there is a replaced string arg which is not variable
4847 result = self.method( self.hyp, *args )
4848 except ValueError, detail: # raised by ParseParameters()
4850 result = self.method( self.hyp, *args )
4851 except omniORB.CORBA.BAD_PARAM:
4852 raise ValueError, detail # wrong variable name
4857 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
4858 class genObjUnRegister:
4860 def __init__(self, genObj=None):
4861 self.genObjList = []
4865 def set(self, genObj):
4866 "Store one or a list of of SALOME.GenericObj'es"
4867 if isinstance( genObj, list ):
4868 self.genObjList.extend( genObj )
4870 self.genObjList.append( genObj )
4874 for genObj in self.genObjList:
4875 if genObj and hasattr( genObj, "UnRegister" ):
4878 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4880 #print "pluginName: ", pluginName
4881 pluginBuilderName = pluginName + "Builder"
4883 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4884 except Exception, e:
4885 from salome_utils import verbose
4886 if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4888 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4889 plugin = eval( pluginBuilderName )
4890 #print " plugin:" , str(plugin)
4892 # add methods creating algorithms to Mesh
4893 for k in dir( plugin ):
4894 if k[0] == '_': continue
4895 algo = getattr( plugin, k )
4896 #print " algo:", str(algo)
4897 if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4898 #print " meshMethod:" , str(algo.meshMethod)
4899 if not hasattr( Mesh, algo.meshMethod ):
4900 setattr( Mesh, algo.meshMethod, algoCreator() )
4902 getattr( Mesh, algo.meshMethod ).add( algo )