1 # Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License, or (at your option) any later version.
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 # File : smeshBuilder.py
20 # Author : Francis KLOSS, OCC
23 ## @package smeshBuilder
24 # Python API for SALOME %Mesh module
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating Creating meshes
29 ## @defgroup l2_impexp Importing and exporting meshes
32 ## These are methods of class \ref smeshBuilder.smeshBuilder "smeshBuilder"
34 ## @defgroup l2_construct Constructing meshes
35 ## @defgroup l2_algorithms Defining Algorithms
37 ## @defgroup l3_algos_basic Basic meshing algorithms
38 ## @defgroup l3_algos_proj Projection Algorithms
39 ## @defgroup l3_algos_segmarv Segments around Vertex
40 ## @defgroup l3_algos_3dextr 3D extrusion meshing algorithm
43 ## @defgroup l2_hypotheses Defining hypotheses
45 ## @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
46 ## @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
47 ## @defgroup l3_hypos_maxvol Max Element Volume hypothesis
48 ## @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
49 ## @defgroup l3_hypos_additi Additional Hypotheses
52 ## @defgroup l2_submeshes Constructing sub-meshes
53 ## @defgroup l2_editing Editing Meshes
56 ## @defgroup l1_meshinfo Mesh Information
57 ## @defgroup l1_controls Quality controls and Filtering
58 ## @defgroup l1_grouping Grouping elements
60 ## @defgroup l2_grps_create Creating groups
61 ## @defgroup l2_grps_operon Using operations on groups
62 ## @defgroup l2_grps_delete Deleting Groups
65 ## @defgroup l1_modifying Modifying meshes
67 ## @defgroup l2_modif_add Adding nodes and elements
68 ## @defgroup l2_modif_del Removing nodes and elements
69 ## @defgroup l2_modif_edit Modifying nodes and elements
70 ## @defgroup l2_modif_renumber Renumbering nodes and elements
71 ## @defgroup l2_modif_trsf Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
72 ## @defgroup l2_modif_unitetri Uniting triangles
73 ## @defgroup l2_modif_cutquadr Cutting elements
74 ## @defgroup l2_modif_changori Changing orientation of elements
75 ## @defgroup l2_modif_smooth Smoothing
76 ## @defgroup l2_modif_extrurev Extrusion and Revolution
77 ## @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
78 ## @defgroup l2_modif_duplicat Duplication of nodes and elements (to emulate cracks)
81 ## @defgroup l1_measurements Measurements
84 from salome.geom import geomBuilder
86 import SMESH # This is necessary for back compatibility
88 from salome.smesh.smesh_algorithm import Mesh_Algorithm
95 # In case the omniORBpy EnumItem class does not fully support Python 3
96 # (for instance in version 4.2.1-2), the comparison ordering methods must be
100 SMESH.Entity_Triangle < SMESH.Entity_Quadrangle
102 def enumitem_eq(self, other):
104 if isinstance(other, omniORB.EnumItem):
105 if other._parent_id == self._parent_id:
106 return self._v == other._v
108 return self._parent_id == other._parent_id
110 return id(self) == id(other)
112 return id(self) == id(other)
114 def enumitem_lt(self, other):
116 if isinstance(other, omniORB.EnumItem):
117 if other._parent_id == self._parent_id:
118 return self._v < other._v
120 return self._parent_id < other._parent_id
122 return id(self) < id(other)
124 return id(self) < id(other)
126 def enumitem_le(self, other):
128 if isinstance(other, omniORB.EnumItem):
129 if other._parent_id == self._parent_id:
130 return self._v <= other._v
132 return self._parent_id <= other._parent_id
134 return id(self) <= id(other)
136 return id(self) <= id(other)
138 def enumitem_gt(self, other):
140 if isinstance(other, omniORB.EnumItem):
141 if other._parent_id == self._parent_id:
142 return self._v > other._v
144 return self._parent_id > other._parent_id
146 return id(self) > id(other)
148 return id(self) > id(other)
150 def enumitem_ge(self, other):
152 if isinstance(other, omniORB.EnumItem):
153 if other._parent_id == self._parent_id:
154 return self._v >= other._v
156 return self._parent_id >= other._parent_id
158 return id(self) >= id(other)
160 return id(self) >= id(other)
162 omniORB.EnumItem.__eq__ = enumitem_eq
163 omniORB.EnumItem.__lt__ = enumitem_lt
164 omniORB.EnumItem.__le__ = enumitem_le
165 omniORB.EnumItem.__gt__ = enumitem_gt
166 omniORB.EnumItem.__ge__ = enumitem_ge
169 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
171 class MeshMeta(type):
172 def __instancecheck__(cls, inst):
173 """Implement isinstance(inst, cls)."""
174 return any(cls.__subclasscheck__(c)
175 for c in {type(inst), inst.__class__})
177 def __subclasscheck__(cls, sub):
178 """Implement issubclass(sub, cls)."""
179 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
181 ## @addtogroup l1_auxiliary
184 ## Convert an angle from degrees to radians
185 def DegreesToRadians(AngleInDegrees):
187 return AngleInDegrees * pi / 180.0
189 import salome_notebook
190 notebook = salome_notebook.notebook
191 # Salome notebook variable separator
194 ## Return list of variable values from salome notebook.
195 # The last argument, if is callable, is used to modify values got from notebook
196 def ParseParameters(*args):
201 if args and callable(args[-1]):
202 args, varModifFun = args[:-1], args[-1]
203 for parameter in args:
205 Parameters += str(parameter) + var_separator
207 if isinstance(parameter,str):
208 # check if there is an inexistent variable name
209 if not notebook.isVariable(parameter):
210 raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
211 parameter = notebook.get(parameter)
214 parameter = varModifFun(parameter)
217 Result.append(parameter)
220 Parameters = Parameters[:-1]
221 Result.append( Parameters )
222 Result.append( hasVariables )
225 ## Parse parameters while converting variables to radians
226 def ParseAngles(*args):
227 return ParseParameters( *( args + (DegreesToRadians, )))
229 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
230 # Parameters are stored in PointStruct.parameters attribute
231 def __initPointStruct(point,*args):
232 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
234 SMESH.PointStruct.__init__ = __initPointStruct
236 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
237 # Parameters are stored in AxisStruct.parameters attribute
238 def __initAxisStruct(ax,*args):
240 raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
241 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
243 SMESH.AxisStruct.__init__ = __initAxisStruct
245 smeshPrecisionConfusion = 1.e-07
246 ## Compare real values using smeshPrecisionConfusion as tolerance
247 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
248 if abs(val1 - val2) < tol:
254 ## Return object name
258 if isinstance(obj, SALOMEDS._objref_SObject):
262 ior = salome.orb.object_to_string(obj)
267 studies = salome.myStudyManager.GetOpenStudies()
268 for sname in studies:
269 s = salome.myStudyManager.GetStudyByName(sname)
271 sobj = s.FindObjectIOR(ior)
272 if not sobj: continue
273 return sobj.GetName()
274 if hasattr(obj, "GetName"):
275 # unknown CORBA object, having GetName() method
278 # unknown CORBA object, no GetName() method
281 if hasattr(obj, "GetName"):
282 # unknown non-CORBA object, having GetName() method
285 raise RuntimeError("Null or invalid object")
287 ## Print error message if a hypothesis was not assigned.
288 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
290 hypType = "algorithm"
292 hypType = "hypothesis"
295 if hasattr( status, "__getitem__" ):
296 status, reason = status[0], status[1]
297 if status == HYP_UNKNOWN_FATAL:
298 reason = "for unknown reason"
299 elif status == HYP_INCOMPATIBLE:
300 reason = "this hypothesis mismatches the algorithm"
301 elif status == HYP_NOTCONFORM:
302 reason = "a non-conform mesh would be built"
303 elif status == HYP_ALREADY_EXIST:
304 if isAlgo: return # it does not influence anything
305 reason = hypType + " of the same dimension is already assigned to this shape"
306 elif status == HYP_BAD_DIM:
307 reason = hypType + " mismatches the shape"
308 elif status == HYP_CONCURENT:
309 reason = "there are concurrent hypotheses on sub-shapes"
310 elif status == HYP_BAD_SUBSHAPE:
311 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
312 elif status == HYP_BAD_GEOMETRY:
313 reason = "the algorithm is not applicable to this geometry"
314 elif status == HYP_HIDDEN_ALGO:
315 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
316 elif status == HYP_HIDING_ALGO:
317 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
318 elif status == HYP_NEED_SHAPE:
319 reason = "algorithm can't work without shape"
320 elif status == HYP_INCOMPAT_HYPS:
326 where = '"%s"' % geomName
328 meshName = GetName( mesh )
329 if meshName and meshName != NO_NAME:
330 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
331 if status < HYP_UNKNOWN_FATAL and where:
332 print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
334 print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
336 print('"%s" was not assigned : %s' %( hypName, reason ))
339 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
340 def AssureGeomPublished(mesh, geom, name=''):
341 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
343 if not geom.GetStudyEntry() and \
344 mesh.smeshpyD.GetCurrentStudy():
346 studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
347 if studyID != mesh.geompyD.myStudyId:
348 mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
350 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
351 # for all groups SubShapeName() return "Compound_-1"
352 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
354 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
356 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
359 ## Return the first vertex of a geometrical edge by ignoring orientation
360 def FirstVertexOnCurve(mesh, edge):
361 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
363 raise TypeError("Given object has no vertices")
364 if len( vv ) == 1: return vv[0]
365 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
366 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
367 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
368 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
371 dist1 += abs( xyz[i] - xyz1[i] )
372 dist2 += abs( xyz[i] - xyz2[i] )
378 ## Return a long value from enumeration
379 def EnumToLong(theItem):
382 # end of l1_auxiliary
386 # Warning: smeshInst is a singleton
392 ## This class allows to create, load or manipulate meshes.
393 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
394 # It also has methods to get infos and measure meshes.
395 class smeshBuilder(SMESH._objref_SMESH_Gen):
397 # MirrorType enumeration
398 POINT = SMESH_MeshEditor.POINT
399 AXIS = SMESH_MeshEditor.AXIS
400 PLANE = SMESH_MeshEditor.PLANE
402 # Smooth_Method enumeration
403 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
404 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
406 PrecisionConfusion = smeshPrecisionConfusion
408 # TopAbs_State enumeration
409 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
411 # Methods of splitting a hexahedron into tetrahedra
412 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
414 def __new__(cls, *args):
418 #print "==== __new__", engine, smeshInst, doLcc
420 if smeshInst is None:
421 # smesh engine is either retrieved from engine, or created
423 # Following test avoids a recursive loop
425 if smeshInst is not None:
426 # smesh engine not created: existing engine found
430 # FindOrLoadComponent called:
431 # 1. CORBA resolution of server
432 # 2. the __new__ method is called again
433 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
434 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
436 # FindOrLoadComponent not called
437 if smeshInst is None:
438 # smeshBuilder instance is created from lcc.FindOrLoadComponent
439 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
440 smeshInst = super(smeshBuilder,cls).__new__(cls)
442 # smesh engine not created: existing engine found
443 #print "==== existing ", engine, smeshInst, doLcc
445 #print "====1 ", smeshInst
448 #print "====2 ", smeshInst
451 def __init__(self, *args):
453 #print "--------------- smeshbuilder __init__ ---", created
456 SMESH._objref_SMESH_Gen.__init__(self, *args)
458 ## Dump component to the Python script
459 # This method overrides IDL function to allow default values for the parameters.
460 # @ingroup l1_auxiliary
461 def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
462 return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
464 ## Set mode of DumpPython(), \a historical or \a snapshot.
465 # In the \a historical mode, the Python Dump script includes all commands
466 # performed by SMESH engine. In the \a snapshot mode, commands
467 # relating to objects removed from the Study are excluded from the script
468 # as well as commands not influencing the current state of meshes
469 # @ingroup l1_auxiliary
470 def SetDumpPythonHistorical(self, isHistorical):
471 if isHistorical: val = "true"
473 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
475 ## Set the current study and Geometry component
476 # @ingroup l1_auxiliary
477 def init_smesh(self,theStudy,geompyD = None):
479 self.SetCurrentStudy(theStudy,geompyD)
482 notebook.myStudy = theStudy
484 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
485 # or a mesh wrapping a CORBA mesh given as a parameter.
486 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
487 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
488 # (2) a Geometrical object for meshing or
490 # @param name the name for the new mesh.
491 # @return an instance of Mesh class.
492 # @ingroup l2_construct
493 def Mesh(self, obj=0, name=0):
494 if isinstance(obj,str):
496 return Mesh(self,self.geompyD,obj,name)
498 ## Return a string representation of the color.
499 # To be used with filters.
500 # @param c color value (SALOMEDS.Color)
501 # @ingroup l1_auxiliary
502 def ColorToString(self,c):
504 if isinstance(c, SALOMEDS.Color):
505 val = "%s;%s;%s" % (c.R, c.G, c.B)
506 elif isinstance(c, str):
509 raise ValueError("Color value should be of string or SALOMEDS.Color type")
512 ## Get PointStruct from vertex
513 # @param theVertex a GEOM object(vertex)
514 # @return SMESH.PointStruct
515 # @ingroup l1_auxiliary
516 def GetPointStruct(self,theVertex):
517 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
518 return PointStruct(x,y,z)
520 ## Get DirStruct from vector
521 # @param theVector a GEOM object(vector)
522 # @return SMESH.DirStruct
523 # @ingroup l1_auxiliary
524 def GetDirStruct(self,theVector):
525 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
526 if(len(vertices) != 2):
527 print("Error: vector object is incorrect.")
529 p1 = self.geompyD.PointCoordinates(vertices[0])
530 p2 = self.geompyD.PointCoordinates(vertices[1])
531 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
532 dirst = DirStruct(pnt)
535 ## Make DirStruct from a triplet
536 # @param x,y,z vector components
537 # @return SMESH.DirStruct
538 # @ingroup l1_auxiliary
539 def MakeDirStruct(self,x,y,z):
540 pnt = PointStruct(x,y,z)
541 return DirStruct(pnt)
543 ## Get AxisStruct from object
544 # @param theObj a GEOM object (line or plane)
545 # @return SMESH.AxisStruct
546 # @ingroup l1_auxiliary
547 def GetAxisStruct(self,theObj):
549 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
552 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
553 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
554 vertex1 = self.geompyD.PointCoordinates(vertex1)
555 vertex2 = self.geompyD.PointCoordinates(vertex2)
556 vertex3 = self.geompyD.PointCoordinates(vertex3)
557 vertex4 = self.geompyD.PointCoordinates(vertex4)
558 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
559 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
560 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] ]
561 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
562 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
563 elif len(edges) == 1:
564 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
565 p1 = self.geompyD.PointCoordinates( vertex1 )
566 p2 = self.geompyD.PointCoordinates( vertex2 )
567 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
568 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
569 elif theObj.GetShapeType() == GEOM.VERTEX:
570 x,y,z = self.geompyD.PointCoordinates( theObj )
571 axis = AxisStruct( x,y,z, 1,0,0,)
572 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
575 # From SMESH_Gen interface:
576 # ------------------------
578 ## Set the given name to the object
579 # @param obj the object to rename
580 # @param name a new object name
581 # @ingroup l1_auxiliary
582 def SetName(self, obj, name):
583 if isinstance( obj, Mesh ):
585 elif isinstance( obj, Mesh_Algorithm ):
586 obj = obj.GetAlgorithm()
587 ior = salome.orb.object_to_string(obj)
588 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
590 ## Set the current mode
591 # @ingroup l1_auxiliary
592 def SetEmbeddedMode( self,theMode ):
593 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
595 ## Get the current mode
596 # @ingroup l1_auxiliary
597 def IsEmbeddedMode(self):
598 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
600 ## Set the current study. Calling SetCurrentStudy( None ) allows to
601 # switch OFF automatic pubilishing in the Study of mesh objects.
602 # @ingroup l1_auxiliary
603 def SetCurrentStudy( self, theStudy, geompyD = None ):
605 from salome.geom import geomBuilder
606 geompyD = geomBuilder.geom
609 self.SetGeomEngine(geompyD)
610 SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
613 notebook = salome_notebook.NoteBook( theStudy )
615 notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
617 sb = theStudy.NewBuilder()
618 sc = theStudy.FindComponent("SMESH")
619 if sc: sb.LoadWith(sc, self)
623 ## Get the current study
624 # @ingroup l1_auxiliary
625 def GetCurrentStudy(self):
626 return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
628 ## Create a Mesh object importing data from the given UNV file
629 # @return an instance of Mesh class
631 def CreateMeshesFromUNV( self,theFileName ):
632 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
633 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
636 ## Create a Mesh object(s) importing data from the given MED file
637 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
639 def CreateMeshesFromMED( self,theFileName ):
640 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
641 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
642 return aMeshes, aStatus
644 ## Create a Mesh object(s) importing data from the given SAUV file
645 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
647 def CreateMeshesFromSAUV( self,theFileName ):
648 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
649 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
650 return aMeshes, aStatus
652 ## Create a Mesh object importing data from the given STL file
653 # @return an instance of Mesh class
655 def CreateMeshesFromSTL( self, theFileName ):
656 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
657 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
660 ## Create Mesh objects importing data from the given CGNS file
661 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
663 def CreateMeshesFromCGNS( self, theFileName ):
664 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
665 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
666 return aMeshes, aStatus
668 ## Create a Mesh object importing data from the given GMF file.
669 # GMF files must have .mesh extension for the ASCII format and .meshb for
671 # @return [ an instance of Mesh class, SMESH.ComputeError ]
673 def CreateMeshesFromGMF( self, theFileName ):
674 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
677 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
678 return Mesh(self, self.geompyD, aSmeshMesh), error
680 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
681 # present in the new mesh.
682 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
683 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
684 # @param mergeNodesAndElements if true, equal nodes and elements are merged
685 # @param mergeTolerance tolerance for merging nodes
686 # @param allGroups forces creation of groups corresponding to every input mesh
687 # @param name name of a new mesh
688 # @return an instance of Mesh class
689 # @ingroup l1_creating
690 def Concatenate( self, meshes, uniteIdenticalGroups,
691 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
693 if not meshes: return None
694 for i,m in enumerate(meshes):
695 if isinstance(m, Mesh):
696 meshes[i] = m.GetMesh()
697 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
698 meshes[0].SetParameters(Parameters)
700 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
701 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
703 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
704 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
705 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
708 ## Create a mesh by copying a part of another mesh.
709 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
710 # to copy nodes or elements not contained in any mesh object,
711 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
712 # @param meshName a name of the new mesh
713 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
714 # @param toKeepIDs to preserve order of the copied elements or not
715 # @return an instance of Mesh class
716 # @ingroup l1_creating
717 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
718 if (isinstance( meshPart, Mesh )):
719 meshPart = meshPart.GetMesh()
720 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
721 return Mesh(self, self.geompyD, mesh)
723 ## Return IDs of sub-shapes
724 # @return the list of integer values
725 # @ingroup l1_auxiliary
726 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
727 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
729 ## Create a pattern mapper.
730 # @return an instance of SMESH_Pattern
732 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
733 # @ingroup l1_modifying
734 def GetPattern(self):
735 return SMESH._objref_SMESH_Gen.GetPattern(self)
737 ## Set number of segments per diagonal of boundary box of geometry, by which
738 # default segment length of appropriate 1D hypotheses is defined in GUI.
739 # Default value is 10.
740 # @ingroup l1_auxiliary
741 def SetBoundaryBoxSegmentation(self, nbSegments):
742 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
744 # Filtering. Auxiliary functions:
745 # ------------------------------
747 ## Create an empty criterion
748 # @return SMESH.Filter.Criterion
749 # @ingroup l1_controls
750 def GetEmptyCriterion(self):
751 Type = EnumToLong(FT_Undefined)
752 Compare = EnumToLong(FT_Undefined)
756 UnaryOp = EnumToLong(FT_Undefined)
757 BinaryOp = EnumToLong(FT_Undefined)
760 Precision = -1 ##@1e-07
761 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
762 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
764 ## Create a criterion by the given parameters
765 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
766 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
767 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
768 # Type SMESH.FunctorType._items in the Python Console to see all values.
769 # Note that the items starting from FT_LessThan are not suitable for CritType.
770 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
771 # @param Threshold the threshold value (range of ids as string, shape, numeric)
772 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
773 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
775 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
776 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
777 # @return SMESH.Filter.Criterion
779 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
780 # @ingroup l1_controls
781 def GetCriterion(self,elementType,
783 Compare = FT_EqualTo,
785 UnaryOp=FT_Undefined,
786 BinaryOp=FT_Undefined,
788 if not CritType in SMESH.FunctorType._items:
789 raise TypeError("CritType should be of SMESH.FunctorType")
790 aCriterion = self.GetEmptyCriterion()
791 aCriterion.TypeOfElement = elementType
792 aCriterion.Type = EnumToLong(CritType)
793 aCriterion.Tolerance = Tolerance
795 aThreshold = Threshold
797 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
798 aCriterion.Compare = EnumToLong(Compare)
799 elif Compare == "=" or Compare == "==":
800 aCriterion.Compare = EnumToLong(FT_EqualTo)
802 aCriterion.Compare = EnumToLong(FT_LessThan)
804 aCriterion.Compare = EnumToLong(FT_MoreThan)
805 elif Compare != FT_Undefined:
806 aCriterion.Compare = EnumToLong(FT_EqualTo)
809 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
810 FT_BelongToCylinder, FT_LyingOnGeom]:
811 # Check that Threshold is GEOM object
812 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
813 aCriterion.ThresholdStr = GetName(aThreshold)
814 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
815 if not aCriterion.ThresholdID:
816 name = aCriterion.ThresholdStr
818 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
819 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
820 # or a name of GEOM object
821 elif isinstance( aThreshold, str ):
822 aCriterion.ThresholdStr = aThreshold
824 raise TypeError("The Threshold should be a shape.")
825 if isinstance(UnaryOp,float):
826 aCriterion.Tolerance = UnaryOp
827 UnaryOp = FT_Undefined
829 elif CritType == FT_BelongToMeshGroup:
830 # Check that Threshold is a group
831 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
832 if aThreshold.GetType() != elementType:
833 raise ValueError("Group type mismatches Element type")
834 aCriterion.ThresholdStr = aThreshold.GetName()
835 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
836 study = self.GetCurrentStudy()
838 so = study.FindObjectIOR( aCriterion.ThresholdID )
842 aCriterion.ThresholdID = entry
844 raise TypeError("The Threshold should be a Mesh Group")
845 elif CritType == FT_RangeOfIds:
846 # Check that Threshold is string
847 if isinstance(aThreshold, str):
848 aCriterion.ThresholdStr = aThreshold
850 raise TypeError("The Threshold should be a string.")
851 elif CritType == FT_CoplanarFaces:
852 # Check the Threshold
853 if isinstance(aThreshold, int):
854 aCriterion.ThresholdID = str(aThreshold)
855 elif isinstance(aThreshold, str):
858 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
859 aCriterion.ThresholdID = aThreshold
861 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
862 elif CritType == FT_ConnectedElements:
863 # Check the Threshold
864 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
865 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
866 if not aCriterion.ThresholdID:
867 name = aThreshold.GetName()
869 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
870 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
871 elif isinstance(aThreshold, int): # node id
872 aCriterion.Threshold = aThreshold
873 elif isinstance(aThreshold, list): # 3 point coordinates
874 if len( aThreshold ) < 3:
875 raise ValueError("too few point coordinates, must be 3")
876 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
877 elif isinstance(aThreshold, str):
878 if aThreshold.isdigit():
879 aCriterion.Threshold = aThreshold # node id
881 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
883 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
884 "or a list of point coordinates and not '%s'"%aThreshold)
885 elif CritType == FT_ElemGeomType:
886 # Check the Threshold
888 aCriterion.Threshold = EnumToLong(aThreshold)
889 assert( aThreshold in SMESH.GeometryType._items )
891 if isinstance(aThreshold, int):
892 aCriterion.Threshold = aThreshold
894 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
897 elif CritType == FT_EntityType:
898 # Check the Threshold
900 aCriterion.Threshold = EnumToLong(aThreshold)
901 assert( aThreshold in SMESH.EntityType._items )
903 if isinstance(aThreshold, int):
904 aCriterion.Threshold = aThreshold
906 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
910 elif CritType == FT_GroupColor:
911 # Check the Threshold
913 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
915 raise TypeError("The threshold value should be of SALOMEDS.Color type")
917 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
918 FT_LinearOrQuadratic, FT_BadOrientedVolume,
919 FT_BareBorderFace, FT_BareBorderVolume,
920 FT_OverConstrainedFace, FT_OverConstrainedVolume,
921 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
922 # At this point the Threshold is unnecessary
923 if aThreshold == FT_LogicalNOT:
924 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
925 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
926 aCriterion.BinaryOp = aThreshold
930 aThreshold = float(aThreshold)
931 aCriterion.Threshold = aThreshold
933 raise TypeError("The Threshold should be a number.")
936 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
937 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
939 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
940 aCriterion.BinaryOp = EnumToLong(Threshold)
942 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
943 aCriterion.BinaryOp = EnumToLong(UnaryOp)
945 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
946 aCriterion.BinaryOp = EnumToLong(BinaryOp)
950 ## Create a filter with the given parameters
951 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
952 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
953 # Type SMESH.FunctorType._items in the Python Console to see all values.
954 # Note that the items starting from FT_LessThan are not suitable for CritType.
955 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
956 # @param Threshold the threshold value (range of ids as string, shape, numeric)
957 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
958 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
959 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
960 # @param mesh the mesh to initialize the filter with
961 # @return SMESH_Filter
963 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
964 # @ingroup l1_controls
965 def GetFilter(self,elementType,
966 CritType=FT_Undefined,
969 UnaryOp=FT_Undefined,
972 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
973 aFilterMgr = self.CreateFilterManager()
974 aFilter = aFilterMgr.CreateFilter()
976 aCriteria.append(aCriterion)
977 aFilter.SetCriteria(aCriteria)
979 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
980 else : aFilter.SetMesh( mesh )
981 aFilterMgr.UnRegister()
984 ## Create a filter from criteria
985 # @param criteria a list of criteria
986 # @param binOp binary operator used when binary operator of criteria is undefined
987 # @return SMESH_Filter
989 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
990 # @ingroup l1_controls
991 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
992 for i in range( len( criteria ) - 1 ):
993 if criteria[i].BinaryOp == EnumToLong( SMESH.FT_Undefined ):
994 criteria[i].BinaryOp = EnumToLong( binOp )
995 aFilterMgr = self.CreateFilterManager()
996 aFilter = aFilterMgr.CreateFilter()
997 aFilter.SetCriteria(criteria)
998 aFilterMgr.UnRegister()
1001 ## Create a numerical functor by its type
1002 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
1003 # Type SMESH.FunctorType._items in the Python Console to see all items.
1004 # Note that not all items correspond to numerical functors.
1005 # @return SMESH_NumericalFunctor
1006 # @ingroup l1_controls
1007 def GetFunctor(self,theCriterion):
1008 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1010 aFilterMgr = self.CreateFilterManager()
1012 if theCriterion == FT_AspectRatio:
1013 functor = aFilterMgr.CreateAspectRatio()
1014 elif theCriterion == FT_AspectRatio3D:
1015 functor = aFilterMgr.CreateAspectRatio3D()
1016 elif theCriterion == FT_Warping:
1017 functor = aFilterMgr.CreateWarping()
1018 elif theCriterion == FT_MinimumAngle:
1019 functor = aFilterMgr.CreateMinimumAngle()
1020 elif theCriterion == FT_Taper:
1021 functor = aFilterMgr.CreateTaper()
1022 elif theCriterion == FT_Skew:
1023 functor = aFilterMgr.CreateSkew()
1024 elif theCriterion == FT_Area:
1025 functor = aFilterMgr.CreateArea()
1026 elif theCriterion == FT_Volume3D:
1027 functor = aFilterMgr.CreateVolume3D()
1028 elif theCriterion == FT_MaxElementLength2D:
1029 functor = aFilterMgr.CreateMaxElementLength2D()
1030 elif theCriterion == FT_MaxElementLength3D:
1031 functor = aFilterMgr.CreateMaxElementLength3D()
1032 elif theCriterion == FT_MultiConnection:
1033 functor = aFilterMgr.CreateMultiConnection()
1034 elif theCriterion == FT_MultiConnection2D:
1035 functor = aFilterMgr.CreateMultiConnection2D()
1036 elif theCriterion == FT_Length:
1037 functor = aFilterMgr.CreateLength()
1038 elif theCriterion == FT_Length2D:
1039 functor = aFilterMgr.CreateLength2D()
1040 elif theCriterion == FT_NodeConnectivityNumber:
1041 functor = aFilterMgr.CreateNodeConnectivityNumber()
1042 elif theCriterion == FT_BallDiameter:
1043 functor = aFilterMgr.CreateBallDiameter()
1045 print("Error: given parameter is not numerical functor type.")
1046 aFilterMgr.UnRegister()
1049 ## Create hypothesis
1050 # @param theHType mesh hypothesis type (string)
1051 # @param theLibName mesh plug-in library name
1052 # @return created hypothesis instance
1053 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1054 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1056 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1059 # wrap hypothesis methods
1060 #print "HYPOTHESIS", theHType
1061 for meth_name in dir( hyp.__class__ ):
1062 if not meth_name.startswith("Get") and \
1063 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1064 method = getattr ( hyp.__class__, meth_name )
1065 if callable(method):
1066 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1070 ## Get the mesh statistic
1071 # @return dictionary "element type" - "count of elements"
1072 # @ingroup l1_meshinfo
1073 def GetMeshInfo(self, obj):
1074 if isinstance( obj, Mesh ):
1077 if hasattr(obj, "GetMeshInfo"):
1078 values = obj.GetMeshInfo()
1079 for i in range(EnumToLong(SMESH.Entity_Last)):
1080 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1084 ## Get minimum distance between two objects
1086 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1087 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1089 # @param src1 first source object
1090 # @param src2 second source object
1091 # @param id1 node/element id from the first source
1092 # @param id2 node/element id from the second (or first) source
1093 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1094 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1095 # @return minimum distance value
1096 # @sa GetMinDistance()
1097 # @ingroup l1_measurements
1098 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1099 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1103 result = result.value
1106 ## Get measure structure specifying minimum distance data between two objects
1108 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1109 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1111 # @param src1 first source object
1112 # @param src2 second source object
1113 # @param id1 node/element id from the first source
1114 # @param id2 node/element id from the second (or first) source
1115 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1116 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1117 # @return Measure structure or None if input data is invalid
1119 # @ingroup l1_measurements
1120 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1121 if isinstance(src1, Mesh): src1 = src1.mesh
1122 if isinstance(src2, Mesh): src2 = src2.mesh
1123 if src2 is None and id2 != 0: src2 = src1
1124 if not hasattr(src1, "_narrow"): return None
1125 src1 = src1._narrow(SMESH.SMESH_IDSource)
1126 if not src1: return None
1127 unRegister = genObjUnRegister()
1130 e = m.GetMeshEditor()
1132 src1 = e.MakeIDSource([id1], SMESH.FACE)
1134 src1 = e.MakeIDSource([id1], SMESH.NODE)
1135 unRegister.set( src1 )
1137 if hasattr(src2, "_narrow"):
1138 src2 = src2._narrow(SMESH.SMESH_IDSource)
1139 if src2 and id2 != 0:
1141 e = m.GetMeshEditor()
1143 src2 = e.MakeIDSource([id2], SMESH.FACE)
1145 src2 = e.MakeIDSource([id2], SMESH.NODE)
1146 unRegister.set( src2 )
1149 aMeasurements = self.CreateMeasurements()
1150 unRegister.set( aMeasurements )
1151 result = aMeasurements.MinDistance(src1, src2)
1154 ## Get bounding box of the specified object(s)
1155 # @param objects single source object or list of source objects
1156 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1157 # @sa GetBoundingBox()
1158 # @ingroup l1_measurements
1159 def BoundingBox(self, objects):
1160 result = self.GetBoundingBox(objects)
1164 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1167 ## Get measure structure specifying bounding box data of the specified object(s)
1168 # @param objects single source object or list of source objects
1169 # @return Measure structure
1171 # @ingroup l1_measurements
1172 def GetBoundingBox(self, objects):
1173 if isinstance(objects, tuple):
1174 objects = list(objects)
1175 if not isinstance(objects, list):
1179 if isinstance(o, Mesh):
1180 srclist.append(o.mesh)
1181 elif hasattr(o, "_narrow"):
1182 src = o._narrow(SMESH.SMESH_IDSource)
1183 if src: srclist.append(src)
1186 aMeasurements = self.CreateMeasurements()
1187 result = aMeasurements.BoundingBox(srclist)
1188 aMeasurements.UnRegister()
1191 ## Get sum of lengths of all 1D elements in the mesh object.
1192 # @param obj mesh, submesh or group
1193 # @return sum of lengths of all 1D elements
1194 # @ingroup l1_measurements
1195 def GetLength(self, obj):
1196 if isinstance(obj, Mesh): obj = obj.mesh
1197 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1198 aMeasurements = self.CreateMeasurements()
1199 value = aMeasurements.Length(obj)
1200 aMeasurements.UnRegister()
1203 ## Get sum of areas of all 2D elements in the mesh object.
1204 # @param obj mesh, submesh or group
1205 # @return sum of areas of all 2D elements
1206 # @ingroup l1_measurements
1207 def GetArea(self, obj):
1208 if isinstance(obj, Mesh): obj = obj.mesh
1209 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1210 aMeasurements = self.CreateMeasurements()
1211 value = aMeasurements.Area(obj)
1212 aMeasurements.UnRegister()
1215 ## Get sum of volumes of all 3D elements in the mesh object.
1216 # @param obj mesh, submesh or group
1217 # @return sum of volumes of all 3D elements
1218 # @ingroup l1_measurements
1219 def GetVolume(self, obj):
1220 if isinstance(obj, Mesh): obj = obj.mesh
1221 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1222 aMeasurements = self.CreateMeasurements()
1223 value = aMeasurements.Volume(obj)
1224 aMeasurements.UnRegister()
1227 pass # end of class smeshBuilder
1230 #Registering the new proxy for SMESH_Gen
1231 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1233 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1234 # interface to create or load meshes.
1239 # salome.salome_init()
1240 # from salome.smesh import smeshBuilder
1241 # smesh = smeshBuilder.New(salome.myStudy)
1243 # @param study SALOME study, generally obtained by salome.myStudy.
1244 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1245 # @return smeshBuilder instance
1247 def New( study, instance=None):
1249 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1250 interface to create or load meshes.
1254 salome.salome_init()
1255 from salome.smesh import smeshBuilder
1256 smesh = smeshBuilder.New(salome.myStudy)
1259 study SALOME study, generally obtained by salome.myStudy.
1260 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1262 smeshBuilder instance
1270 smeshInst = smeshBuilder()
1271 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1272 smeshInst.init_smesh(study)
1276 # Public class: Mesh
1277 # ==================
1279 ## This class allows defining and managing a mesh.
1280 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1281 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1282 # new nodes and elements and by changing the existing entities), to get information
1283 # about a mesh and to export a mesh in different formats.
1284 class Mesh(metaclass=MeshMeta):
1291 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1292 # sets the GUI name of this mesh to \a name.
1293 # @param smeshpyD an instance of smeshBuilder class
1294 # @param geompyD an instance of geomBuilder class
1295 # @param obj Shape to be meshed or SMESH_Mesh object
1296 # @param name Study name of the mesh
1297 # @ingroup l2_construct
1298 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1299 self.smeshpyD = smeshpyD
1300 self.geompyD = geompyD
1305 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1308 # publish geom of mesh (issue 0021122)
1309 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1311 studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1312 if studyID != geompyD.myStudyId:
1313 geompyD.init_geom( smeshpyD.GetCurrentStudy())
1316 geo_name = name + " shape"
1318 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1319 geompyD.addToStudy( self.geom, geo_name )
1320 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1322 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1325 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1327 self.smeshpyD.SetName(self.mesh, name)
1329 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1332 self.geom = self.mesh.GetShapeToMesh()
1334 self.editor = self.mesh.GetMeshEditor()
1335 self.functors = [None] * EnumToLong(SMESH.FT_Undefined)
1337 # set self to algoCreator's
1338 for attrName in dir(self):
1339 attr = getattr( self, attrName )
1340 if isinstance( attr, algoCreator ):
1341 setattr( self, attrName, attr.copy( self ))
1346 ## Destructor. Clean-up resources
1349 #self.mesh.UnRegister()
1353 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1354 # @param theMesh a SMESH_Mesh object
1355 # @ingroup l2_construct
1356 def SetMesh(self, theMesh):
1357 # do not call Register() as this prevents mesh servant deletion at closing study
1358 #if self.mesh: self.mesh.UnRegister()
1361 #self.mesh.Register()
1362 self.geom = self.mesh.GetShapeToMesh()
1365 ## Return the mesh, that is an instance of SMESH_Mesh interface
1366 # @return a SMESH_Mesh object
1367 # @ingroup l2_construct
1371 ## Get the name of the mesh
1372 # @return the name of the mesh as a string
1373 # @ingroup l2_construct
1375 name = GetName(self.GetMesh())
1378 ## Set a name to the mesh
1379 # @param name a new name of the mesh
1380 # @ingroup l2_construct
1381 def SetName(self, name):
1382 self.smeshpyD.SetName(self.GetMesh(), name)
1384 ## Get a sub-mesh object associated to a \a geom geometrical object.
1385 # @param geom a geometrical object (shape)
1386 # @param name a name for the sub-mesh in the Object Browser
1387 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1388 # which lies on the given shape
1390 # The sub-mesh object gives access to the IDs of nodes and elements.
1391 # The sub-mesh object has the following methods:
1392 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1393 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1394 # - SMESH.SMESH_subMesh.GetElementsId()
1395 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1396 # - SMESH.SMESH_subMesh.GetNodesId()
1397 # - SMESH.SMESH_subMesh.GetSubShape()
1398 # - SMESH.SMESH_subMesh.GetFather()
1399 # - SMESH.SMESH_subMesh.GetId()
1400 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1401 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1402 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1403 # The created sub-mesh can be retrieved from the algorithm:
1404 # <code>submesh = algo1D.GetSubMesh()</code>
1405 # @ingroup l2_submeshes
1406 def GetSubMesh(self, geom, name):
1407 AssureGeomPublished( self, geom, name )
1408 submesh = self.mesh.GetSubMesh( geom, name )
1411 ## Return the shape associated to the mesh
1412 # @return a GEOM_Object
1413 # @ingroup l2_construct
1417 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1418 # @param geom the shape to be meshed (GEOM_Object)
1419 # @ingroup l2_construct
1420 def SetShape(self, geom):
1421 self.mesh = self.smeshpyD.CreateMesh(geom)
1423 ## Load mesh from the study after opening the study
1427 ## Return true if the hypotheses are defined well
1428 # @param theSubObject a sub-shape of a mesh shape
1429 # @return True or False
1430 # @ingroup l2_construct
1431 def IsReadyToCompute(self, theSubObject):
1432 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1434 ## Return errors of hypotheses definition.
1435 # The list of errors is empty if everything is OK.
1436 # @param theSubObject a sub-shape of a mesh shape
1437 # @return a list of errors
1438 # @ingroup l2_construct
1439 def GetAlgoState(self, theSubObject):
1440 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1442 ## Return a geometrical object on which the given element was built.
1443 # The returned geometrical object, if not nil, is either found in the
1444 # study or published by this method with the given name
1445 # @param theElementID the id of the mesh element
1446 # @param theGeomName the user-defined name of the geometrical object
1447 # @return GEOM::GEOM_Object instance
1448 # @ingroup l1_meshinfo
1449 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1450 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1452 ## Return the mesh dimension depending on the dimension of the underlying shape
1453 # or, if the mesh is not based on any shape, basing on deimension of elements
1454 # @return mesh dimension as an integer value [0,3]
1455 # @ingroup l1_meshinfo
1456 def MeshDimension(self):
1457 if self.mesh.HasShapeToMesh():
1458 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1459 if len( shells ) > 0 :
1461 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1463 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1468 if self.NbVolumes() > 0: return 3
1469 if self.NbFaces() > 0: return 2
1470 if self.NbEdges() > 0: return 1
1473 ## Evaluate size of prospective mesh on a shape
1474 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1475 # To know predicted number of e.g. edges, inquire it this way
1476 # Evaluate()[ EnumToLong( Entity_Edge )]
1477 # @ingroup l2_construct
1478 def Evaluate(self, geom=0):
1479 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1481 geom = self.mesh.GetShapeToMesh()
1484 return self.smeshpyD.Evaluate(self.mesh, geom)
1487 ## Compute the mesh and return the status of the computation
1488 # @param geom geomtrical shape on which mesh data should be computed
1489 # @param discardModifs if True and the mesh has been edited since
1490 # a last total re-compute and that may prevent successful partial re-compute,
1491 # then the mesh is cleaned before Compute()
1492 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1493 # @return True or False
1494 # @ingroup l2_construct
1495 def Compute(self, geom=0, discardModifs=False, refresh=False):
1496 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1498 geom = self.mesh.GetShapeToMesh()
1503 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1505 ok = self.smeshpyD.Compute(self.mesh, geom)
1506 except SALOME.SALOME_Exception as ex:
1507 print("Mesh computation failed, exception caught:")
1508 print(" ", ex.details.text)
1511 print("Mesh computation failed, exception caught:")
1512 traceback.print_exc()
1516 # Treat compute errors
1517 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1519 for err in computeErrors:
1520 if self.mesh.HasShapeToMesh():
1521 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1523 stdErrors = ["OK", #COMPERR_OK
1524 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1525 "std::exception", #COMPERR_STD_EXCEPTION
1526 "OCC exception", #COMPERR_OCC_EXCEPTION
1527 "..", #COMPERR_SLM_EXCEPTION
1528 "Unknown exception", #COMPERR_EXCEPTION
1529 "Memory allocation problem", #COMPERR_MEMORY_PB
1530 "Algorithm failed", #COMPERR_ALGO_FAILED
1531 "Unexpected geometry", #COMPERR_BAD_SHAPE
1532 "Warning", #COMPERR_WARNING
1533 "Computation cancelled",#COMPERR_CANCELED
1534 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1536 if err.code < len(stdErrors): errText = stdErrors[err.code]
1538 errText = "code %s" % -err.code
1539 if errText: errText += ". "
1540 errText += err.comment
1541 if allReasons: allReasons += "\n"
1543 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1545 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1549 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1551 if err.isGlobalAlgo:
1559 reason = '%s %sD algorithm is missing' % (glob, dim)
1560 elif err.state == HYP_MISSING:
1561 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1562 % (glob, dim, name, dim))
1563 elif err.state == HYP_NOTCONFORM:
1564 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1565 elif err.state == HYP_BAD_PARAMETER:
1566 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1567 % ( glob, dim, name ))
1568 elif err.state == HYP_BAD_GEOMETRY:
1569 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1570 'geometry' % ( glob, dim, name ))
1571 elif err.state == HYP_HIDDEN_ALGO:
1572 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1573 'algorithm of upper dimension generating %sD mesh'
1574 % ( glob, dim, name, glob, dim ))
1576 reason = ("For unknown reason. "
1577 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1579 if allReasons: allReasons += "\n"
1580 allReasons += "- " + reason
1582 if not ok or allReasons != "":
1583 msg = '"' + GetName(self.mesh) + '"'
1584 if ok: msg += " has been computed with warnings"
1585 else: msg += " has not been computed"
1586 if allReasons != "": msg += ":"
1591 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1592 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1593 smeshgui = salome.ImportComponentGUI("SMESH")
1594 smeshgui.Init(self.mesh.GetStudyId())
1595 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1596 if refresh: salome.sg.updateObjBrowser(True)
1600 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1601 # @ingroup l2_construct
1602 def GetComputeErrors(self, shape=0 ):
1604 shape = self.mesh.GetShapeToMesh()
1605 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1607 ## Return a name of a sub-shape by its ID
1608 # @param subShapeID a unique ID of a sub-shape
1609 # @return a string describing the sub-shape; possible variants:
1610 # - "Face_12" (published sub-shape)
1611 # - FACE #3 (not published sub-shape)
1612 # - sub-shape #3 (invalid sub-shape ID)
1613 # - #3 (error in this function)
1614 # @ingroup l1_auxiliary
1615 def GetSubShapeName(self, subShapeID ):
1616 if not self.mesh.HasShapeToMesh():
1620 mainIOR = salome.orb.object_to_string( self.GetShape() )
1621 for sname in salome.myStudyManager.GetOpenStudies():
1622 s = salome.myStudyManager.GetStudyByName(sname)
1624 mainSO = s.FindObjectIOR(mainIOR)
1625 if not mainSO: continue
1627 shapeText = '"%s"' % mainSO.GetName()
1628 subIt = s.NewChildIterator(mainSO)
1630 subSO = subIt.Value()
1632 obj = subSO.GetObject()
1633 if not obj: continue
1634 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1637 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1640 if ids == subShapeID:
1641 shapeText = '"%s"' % subSO.GetName()
1644 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1646 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1648 shapeText = 'sub-shape #%s' % (subShapeID)
1650 shapeText = "#%s" % (subShapeID)
1653 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1654 # error of an algorithm
1655 # @param publish if @c True, the returned groups will be published in the study
1656 # @return a list of GEOM groups each named after a failed algorithm
1657 # @ingroup l2_construct
1658 def GetFailedShapes(self, publish=False):
1661 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1662 for err in computeErrors:
1663 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1664 if not shape: continue
1665 if err.algoName in algo2shapes:
1666 algo2shapes[ err.algoName ].append( shape )
1668 algo2shapes[ err.algoName ] = [ shape ]
1672 for algoName, shapes in list(algo2shapes.items()):
1674 groupType = EnumToLong( shapes[0].GetShapeType() )
1675 otherTypeShapes = []
1677 group = self.geompyD.CreateGroup( self.geom, groupType )
1678 for shape in shapes:
1679 if shape.GetShapeType() == shapes[0].GetShapeType():
1680 sameTypeShapes.append( shape )
1682 otherTypeShapes.append( shape )
1683 self.geompyD.UnionList( group, sameTypeShapes )
1685 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1687 group.SetName( algoName )
1688 groups.append( group )
1689 shapes = otherTypeShapes
1692 for group in groups:
1693 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1696 ## Return sub-mesh objects list in meshing order
1697 # @return list of lists of sub-meshes
1698 # @ingroup l2_construct
1699 def GetMeshOrder(self):
1700 return self.mesh.GetMeshOrder()
1702 ## Set order in which concurrent sub-meshes should be meshed
1703 # @param submeshes list of lists of sub-meshes
1704 # @ingroup l2_construct
1705 def SetMeshOrder(self, submeshes):
1706 return self.mesh.SetMeshOrder(submeshes)
1708 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1709 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1710 # @ingroup l2_construct
1711 def Clear(self, refresh=False):
1713 if ( salome.sg.hasDesktop() and
1714 salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1715 smeshgui = salome.ImportComponentGUI("SMESH")
1716 smeshgui.Init(self.mesh.GetStudyId())
1717 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1718 if refresh: salome.sg.updateObjBrowser(True)
1720 ## Remove all nodes and elements of indicated shape
1721 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1722 # @param geomId the ID of a sub-shape to remove elements on
1723 # @ingroup l2_submeshes
1724 def ClearSubMesh(self, geomId, refresh=False):
1725 self.mesh.ClearSubMesh(geomId)
1726 if salome.sg.hasDesktop():
1727 smeshgui = salome.ImportComponentGUI("SMESH")
1728 smeshgui.Init(self.mesh.GetStudyId())
1729 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1730 if refresh: salome.sg.updateObjBrowser(True)
1732 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1733 # @param fineness [0.0,1.0] defines mesh fineness
1734 # @return True or False
1735 # @ingroup l3_algos_basic
1736 def AutomaticTetrahedralization(self, fineness=0):
1737 dim = self.MeshDimension()
1739 self.RemoveGlobalHypotheses()
1740 self.Segment().AutomaticLength(fineness)
1742 self.Triangle().LengthFromEdges()
1747 return self.Compute()
1749 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1750 # @param fineness [0.0, 1.0] defines mesh fineness
1751 # @return True or False
1752 # @ingroup l3_algos_basic
1753 def AutomaticHexahedralization(self, fineness=0):
1754 dim = self.MeshDimension()
1755 # assign the hypotheses
1756 self.RemoveGlobalHypotheses()
1757 self.Segment().AutomaticLength(fineness)
1764 return self.Compute()
1766 ## Assign a hypothesis
1767 # @param hyp a hypothesis to assign
1768 # @param geom a subhape of mesh geometry
1769 # @return SMESH.Hypothesis_Status
1770 # @ingroup l2_editing
1771 def AddHypothesis(self, hyp, geom=0):
1772 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1773 hyp, geom = geom, hyp
1774 if isinstance( hyp, Mesh_Algorithm ):
1775 hyp = hyp.GetAlgorithm()
1780 geom = self.mesh.GetShapeToMesh()
1783 if self.mesh.HasShapeToMesh():
1784 hyp_type = hyp.GetName()
1785 lib_name = hyp.GetLibName()
1786 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1787 # if checkAll and geom:
1788 # checkAll = geom.GetType() == 37
1790 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1792 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1793 status = self.mesh.AddHypothesis(geom, hyp)
1795 status = HYP_BAD_GEOMETRY, ""
1796 hyp_name = GetName( hyp )
1799 geom_name = geom.GetName()
1800 isAlgo = hyp._narrow( SMESH_Algo )
1801 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1804 ## Return True if an algorithm of hypothesis is assigned to a given shape
1805 # @param hyp a hypothesis to check
1806 # @param geom a subhape of mesh geometry
1807 # @return True of False
1808 # @ingroup l2_editing
1809 def IsUsedHypothesis(self, hyp, geom):
1810 if not hyp: # or not geom
1812 if isinstance( hyp, Mesh_Algorithm ):
1813 hyp = hyp.GetAlgorithm()
1815 hyps = self.GetHypothesisList(geom)
1817 if h.GetId() == hyp.GetId():
1821 ## Unassign a hypothesis
1822 # @param hyp a hypothesis to unassign
1823 # @param geom a sub-shape of mesh geometry
1824 # @return SMESH.Hypothesis_Status
1825 # @ingroup l2_editing
1826 def RemoveHypothesis(self, hyp, geom=0):
1829 if isinstance( hyp, Mesh_Algorithm ):
1830 hyp = hyp.GetAlgorithm()
1836 if self.IsUsedHypothesis( hyp, shape ):
1837 return self.mesh.RemoveHypothesis( shape, hyp )
1838 hypName = GetName( hyp )
1839 geoName = GetName( shape )
1840 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
1843 ## Get the list of hypotheses added on a geometry
1844 # @param geom a sub-shape of mesh geometry
1845 # @return the sequence of SMESH_Hypothesis
1846 # @ingroup l2_editing
1847 def GetHypothesisList(self, geom):
1848 return self.mesh.GetHypothesisList( geom )
1850 ## Remove all global hypotheses
1851 # @ingroup l2_editing
1852 def RemoveGlobalHypotheses(self):
1853 current_hyps = self.mesh.GetHypothesisList( self.geom )
1854 for hyp in current_hyps:
1855 self.mesh.RemoveHypothesis( self.geom, hyp )
1859 ## Export the mesh in a file in MED format
1860 ## allowing to overwrite the file if it exists or add the exported data to its contents
1861 # @param f is the file name
1862 # @param auto_groups boolean parameter for creating/not creating
1863 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1864 # the typical use is auto_groups=False.
1865 # @param version MED format version (MED_V2_1 or MED_V2_2,
1866 # the latter meaning any current version). The parameter is
1867 # obsolete since MED_V2_1 is no longer supported.
1868 # @param overwrite boolean parameter for overwriting/not overwriting the file
1869 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1870 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1871 # - 1D if all mesh nodes lie on OX coordinate axis, or
1872 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1873 # - 3D in the rest cases.<br>
1874 # If @a autoDimension is @c False, the space dimension is always 3.
1875 # @param fields list of GEOM fields defined on the shape to mesh.
1876 # @param geomAssocFields each character of this string means a need to export a
1877 # corresponding field; correspondence between fields and characters is following:
1878 # - 'v' stands for "_vertices _" field;
1879 # - 'e' stands for "_edges _" field;
1880 # - 'f' stands for "_faces _" field;
1881 # - 's' stands for "_solids _" field.
1882 # @ingroup l2_impexp
1883 def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1884 overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1885 if meshPart or fields or geomAssocFields:
1886 unRegister = genObjUnRegister()
1887 if isinstance( meshPart, list ):
1888 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1889 unRegister.set( meshPart )
1890 self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1891 fields, geomAssocFields)
1893 self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1895 ## Export the mesh in a file in SAUV format
1896 # @param f is the file name
1897 # @param auto_groups boolean parameter for creating/not creating
1898 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1899 # the typical use is auto_groups=false.
1900 # @ingroup l2_impexp
1901 def ExportSAUV(self, f, auto_groups=0):
1902 self.mesh.ExportSAUV(f, auto_groups)
1904 ## Export the mesh in a file in DAT format
1905 # @param f the file name
1906 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1907 # @ingroup l2_impexp
1908 def ExportDAT(self, f, meshPart=None):
1910 unRegister = genObjUnRegister()
1911 if isinstance( meshPart, list ):
1912 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1913 unRegister.set( meshPart )
1914 self.mesh.ExportPartToDAT( meshPart, f )
1916 self.mesh.ExportDAT(f)
1918 ## Export the mesh in a file in UNV format
1919 # @param f the file name
1920 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1921 # @ingroup l2_impexp
1922 def ExportUNV(self, f, meshPart=None):
1924 unRegister = genObjUnRegister()
1925 if isinstance( meshPart, list ):
1926 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1927 unRegister.set( meshPart )
1928 self.mesh.ExportPartToUNV( meshPart, f )
1930 self.mesh.ExportUNV(f)
1932 ## Export the mesh in a file in STL format
1933 # @param f the file name
1934 # @param ascii defines the file encoding
1935 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1936 # @ingroup l2_impexp
1937 def ExportSTL(self, f, ascii=1, meshPart=None):
1939 unRegister = genObjUnRegister()
1940 if isinstance( meshPart, list ):
1941 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1942 unRegister.set( meshPart )
1943 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1945 self.mesh.ExportSTL(f, ascii)
1947 ## Export the mesh in a file in CGNS format
1948 # @param f is the file name
1949 # @param overwrite boolean parameter for overwriting/not overwriting the file
1950 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1951 # @ingroup l2_impexp
1952 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1953 unRegister = genObjUnRegister()
1954 if isinstance( meshPart, list ):
1955 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1956 unRegister.set( meshPart )
1957 if isinstance( meshPart, Mesh ):
1958 meshPart = meshPart.mesh
1960 meshPart = self.mesh
1961 self.mesh.ExportCGNS(meshPart, f, overwrite)
1963 ## Export the mesh in a file in GMF format.
1964 # GMF files must have .mesh extension for the ASCII format and .meshb for
1965 # the bynary format. Other extensions are not allowed.
1966 # @param f is the file name
1967 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1968 # @ingroup l2_impexp
1969 def ExportGMF(self, f, meshPart=None):
1970 unRegister = genObjUnRegister()
1971 if isinstance( meshPart, list ):
1972 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1973 unRegister.set( meshPart )
1974 if isinstance( meshPart, Mesh ):
1975 meshPart = meshPart.mesh
1977 meshPart = self.mesh
1978 self.mesh.ExportGMF(meshPart, f, True)
1980 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1981 # Export the mesh in a file in MED format
1982 # allowing to overwrite the file if it exists or add the exported data to its contents
1983 # @param f the file name
1984 # @param version MED format version (MED_V2_1 or MED_V2_2,
1985 # the latter meaning any current version). The parameter is
1986 # obsolete since MED_V2_1 is no longer supported.
1987 # @param opt boolean parameter for creating/not creating
1988 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1989 # @param overwrite boolean parameter for overwriting/not overwriting the file
1990 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1991 # - 1D if all mesh nodes lie on OX coordinate axis, or
1992 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1993 # - 3D in the rest cases.<br>
1994 # If @a autoDimension is @c False, the space dimension is always 3.
1995 # @ingroup l2_impexp
1996 def ExportToMED(self, f, version=MED_V2_2, opt=0, overwrite=1, autoDimension=True):
1997 self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1999 # Operations with groups:
2000 # ----------------------
2002 ## Create an empty mesh group
2003 # @param elementType the type of elements in the group; either of
2004 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2005 # @param name the name of the mesh group
2006 # @return SMESH_Group
2007 # @ingroup l2_grps_create
2008 def CreateEmptyGroup(self, elementType, name):
2009 return self.mesh.CreateGroup(elementType, name)
2011 ## Create a mesh group based on the geometric object \a grp
2012 # and gives a \a name, \n if this parameter is not defined
2013 # the name is the same as the geometric group name \n
2014 # Note: Works like GroupOnGeom().
2015 # @param grp a geometric group, a vertex, an edge, a face or a solid
2016 # @param name the name of the mesh group
2017 # @return SMESH_GroupOnGeom
2018 # @ingroup l2_grps_create
2019 def Group(self, grp, name=""):
2020 return self.GroupOnGeom(grp, name)
2022 ## Create a mesh group based on the geometrical object \a grp
2023 # and gives a \a name, \n if this parameter is not defined
2024 # the name is the same as the geometrical group name
2025 # @param grp a geometrical group, a vertex, an edge, a face or a solid
2026 # @param name the name of the mesh group
2027 # @param typ the type of elements in the group; either of
2028 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2029 # automatically detected by the type of the geometry
2030 # @return SMESH_GroupOnGeom
2031 # @ingroup l2_grps_create
2032 def GroupOnGeom(self, grp, name="", typ=None):
2033 AssureGeomPublished( self, grp, name )
2035 name = grp.GetName()
2037 typ = self._groupTypeFromShape( grp )
2038 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2040 ## Pivate method to get a type of group on geometry
2041 def _groupTypeFromShape( self, shape ):
2042 tgeo = str(shape.GetShapeType())
2043 if tgeo == "VERTEX":
2045 elif tgeo == "EDGE":
2047 elif tgeo == "FACE" or tgeo == "SHELL":
2049 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2051 elif tgeo == "COMPOUND":
2052 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2054 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2055 return self._groupTypeFromShape( sub[0] )
2057 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2060 ## Create a mesh group with given \a name based on the \a filter which
2061 ## is a special type of group dynamically updating it's contents during
2062 ## mesh modification
2063 # @param typ the type of elements in the group; either of
2064 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2065 # @param name the name of the mesh group
2066 # @param filter the filter defining group contents
2067 # @return SMESH_GroupOnFilter
2068 # @ingroup l2_grps_create
2069 def GroupOnFilter(self, typ, name, filter):
2070 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2072 ## Create a mesh group by the given ids of elements
2073 # @param groupName the name of the mesh group
2074 # @param elementType the type of elements in the group; either of
2075 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2076 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2077 # @return SMESH_Group
2078 # @ingroup l2_grps_create
2079 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2080 group = self.mesh.CreateGroup(elementType, groupName)
2081 if hasattr( elemIDs, "GetIDs" ):
2082 if hasattr( elemIDs, "SetMesh" ):
2083 elemIDs.SetMesh( self.GetMesh() )
2084 group.AddFrom( elemIDs )
2089 ## Create a mesh group by the given conditions
2090 # @param groupName the name of the mesh group
2091 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2092 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2093 # Type SMESH.FunctorType._items in the Python Console to see all values.
2094 # Note that the items starting from FT_LessThan are not suitable for CritType.
2095 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2096 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2097 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2098 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2099 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2100 # @return SMESH_GroupOnFilter
2101 # @ingroup l2_grps_create
2105 CritType=FT_Undefined,
2108 UnaryOp=FT_Undefined,
2110 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2111 group = self.MakeGroupByCriterion(groupName, aCriterion)
2114 ## Create a mesh group by the given criterion
2115 # @param groupName the name of the mesh group
2116 # @param Criterion the instance of Criterion class
2117 # @return SMESH_GroupOnFilter
2118 # @ingroup l2_grps_create
2119 def MakeGroupByCriterion(self, groupName, Criterion):
2120 return self.MakeGroupByCriteria( groupName, [Criterion] )
2122 ## Create a mesh group by the given criteria (list of criteria)
2123 # @param groupName the name of the mesh group
2124 # @param theCriteria the list of criteria
2125 # @param binOp binary operator used when binary operator of criteria is undefined
2126 # @return SMESH_GroupOnFilter
2127 # @ingroup l2_grps_create
2128 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2129 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2130 group = self.MakeGroupByFilter(groupName, aFilter)
2133 ## Create a mesh group by the given filter
2134 # @param groupName the name of the mesh group
2135 # @param theFilter the instance of Filter class
2136 # @return SMESH_GroupOnFilter
2137 # @ingroup l2_grps_create
2138 def MakeGroupByFilter(self, groupName, theFilter):
2139 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2140 #theFilter.SetMesh( self.mesh )
2141 #group.AddFrom( theFilter )
2142 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2146 # @ingroup l2_grps_delete
2147 def RemoveGroup(self, group):
2148 self.mesh.RemoveGroup(group)
2150 ## Remove a group with its contents
2151 # @ingroup l2_grps_delete
2152 def RemoveGroupWithContents(self, group):
2153 self.mesh.RemoveGroupWithContents(group)
2155 ## Get the list of groups existing in the mesh in the order
2156 # of creation (starting from the oldest one)
2157 # @param elemType type of elements the groups contain; either of
2158 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2159 # by default groups of elements of all types are returned
2160 # @return a sequence of SMESH_GroupBase
2161 # @ingroup l2_grps_create
2162 def GetGroups(self, elemType = SMESH.ALL):
2163 groups = self.mesh.GetGroups()
2164 if elemType == SMESH.ALL:
2168 if g.GetType() == elemType:
2169 typedGroups.append( g )
2174 ## Get the number of groups existing in the mesh
2175 # @return the quantity of groups as an integer value
2176 # @ingroup l2_grps_create
2178 return self.mesh.NbGroups()
2180 ## Get the list of names of groups existing in the mesh
2181 # @return list of strings
2182 # @ingroup l2_grps_create
2183 def GetGroupNames(self):
2184 groups = self.GetGroups()
2186 for group in groups:
2187 names.append(group.GetName())
2190 ## Find groups by name and type
2191 # @param name name of the group of interest
2192 # @param elemType type of elements the groups contain; either of
2193 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2194 # by default one group of any type of elements is returned
2195 # if elemType == SMESH.ALL then all groups of any type are returned
2196 # @return a list of SMESH_GroupBase's
2197 # @ingroup l2_grps_create
2198 def GetGroupByName(self, name, elemType = None):
2200 for group in self.GetGroups():
2201 if group.GetName() == name:
2202 if elemType is None:
2204 if ( elemType == SMESH.ALL or
2205 group.GetType() == elemType ):
2206 groups.append( group )
2209 ## Produce a union of two groups.
2210 # A new group is created. All mesh elements that are
2211 # present in the initial groups are added to the new one
2212 # @return an instance of SMESH_Group
2213 # @ingroup l2_grps_operon
2214 def UnionGroups(self, group1, group2, name):
2215 return self.mesh.UnionGroups(group1, group2, name)
2217 ## Produce a union list of groups.
2218 # New group is created. All mesh elements that are present in
2219 # initial groups are added to the new one
2220 # @return an instance of SMESH_Group
2221 # @ingroup l2_grps_operon
2222 def UnionListOfGroups(self, groups, name):
2223 return self.mesh.UnionListOfGroups(groups, name)
2225 ## Prodice an intersection of two groups.
2226 # A new group is created. All mesh elements that are common
2227 # for the two initial groups are added to the new one.
2228 # @return an instance of SMESH_Group
2229 # @ingroup l2_grps_operon
2230 def IntersectGroups(self, group1, group2, name):
2231 return self.mesh.IntersectGroups(group1, group2, name)
2233 ## Produce an intersection of groups.
2234 # New group is created. All mesh elements that are present in all
2235 # initial groups simultaneously are added to the new one
2236 # @return an instance of SMESH_Group
2237 # @ingroup l2_grps_operon
2238 def IntersectListOfGroups(self, groups, name):
2239 return self.mesh.IntersectListOfGroups(groups, name)
2241 ## Produce a cut of two groups.
2242 # A new group is created. All mesh elements that are present in
2243 # the main group but are not present in the tool group are added to the new one
2244 # @return an instance of SMESH_Group
2245 # @ingroup l2_grps_operon
2246 def CutGroups(self, main_group, tool_group, name):
2247 return self.mesh.CutGroups(main_group, tool_group, name)
2249 ## Produce a cut of groups.
2250 # A new group is created. All mesh elements that are present in main groups
2251 # but do not present in tool groups are added to the new one
2252 # @return an instance of SMESH_Group
2253 # @ingroup l2_grps_operon
2254 def CutListOfGroups(self, main_groups, tool_groups, name):
2255 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2258 # Create a standalone group of entities basing on nodes of other groups.
2259 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2260 # \param elemType - a type of elements to include to the new group; either of
2261 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2262 # \param name - a name of the new group.
2263 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2264 # basing on number of element nodes common with reference \a groups.
2265 # Meaning of possible values are:
2266 # - SMESH.ALL_NODES - include if all nodes are common,
2267 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2268 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2269 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2270 # \param underlyingOnly - if \c True (default), an element is included to the
2271 # new group provided that it is based on nodes of an element of \a groups;
2272 # in this case the reference \a groups are supposed to be of higher dimension
2273 # than \a elemType, which can be useful for example to get all faces lying on
2274 # volumes of the reference \a groups.
2275 # @return an instance of SMESH_Group
2276 # @ingroup l2_grps_operon
2277 def CreateDimGroup(self, groups, elemType, name,
2278 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2279 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2281 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2284 ## Convert group on geom into standalone group
2285 # @ingroup l2_grps_operon
2286 def ConvertToStandalone(self, group):
2287 return self.mesh.ConvertToStandalone(group)
2289 # Get some info about mesh:
2290 # ------------------------
2292 ## Return the log of nodes and elements added or removed
2293 # since the previous clear of the log.
2294 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2295 # @return list of log_block structures:
2300 # @ingroup l1_auxiliary
2301 def GetLog(self, clearAfterGet):
2302 return self.mesh.GetLog(clearAfterGet)
2304 ## Clear the log of nodes and elements added or removed since the previous
2305 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2306 # @ingroup l1_auxiliary
2308 self.mesh.ClearLog()
2310 ## Toggle auto color mode on the object.
2311 # @param theAutoColor the flag which toggles auto color mode.
2313 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2314 # @ingroup l1_grouping
2315 def SetAutoColor(self, theAutoColor):
2316 self.mesh.SetAutoColor(theAutoColor)
2318 ## Get flag of object auto color mode.
2319 # @return True or False
2320 # @ingroup l1_grouping
2321 def GetAutoColor(self):
2322 return self.mesh.GetAutoColor()
2324 ## Get the internal ID
2325 # @return integer value, which is the internal Id of the mesh
2326 # @ingroup l1_auxiliary
2328 return self.mesh.GetId()
2331 # @return integer value, which is the study Id of the mesh
2332 # @ingroup l1_auxiliary
2333 def GetStudyId(self):
2334 return self.mesh.GetStudyId()
2336 ## Check the group names for duplications.
2337 # Consider the maximum group name length stored in MED file.
2338 # @return True or False
2339 # @ingroup l1_grouping
2340 def HasDuplicatedGroupNamesMED(self):
2341 return self.mesh.HasDuplicatedGroupNamesMED()
2343 ## Obtain the mesh editor tool
2344 # @return an instance of SMESH_MeshEditor
2345 # @ingroup l1_modifying
2346 def GetMeshEditor(self):
2349 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2350 # can be passed as argument to a method accepting mesh, group or sub-mesh
2351 # @param ids list of IDs
2352 # @param elemType type of elements; this parameter is used to distinguish
2353 # IDs of nodes from IDs of elements; by default ids are treated as
2354 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2355 # @return an instance of SMESH_IDSource
2356 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2357 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2358 # mesh.DoSomething( idSrc )
2359 # idSrc.UnRegister()
2360 # @ingroup l1_auxiliary
2361 def GetIDSource(self, ids, elemType = SMESH.ALL):
2362 if isinstance( ids, int ):
2364 return self.editor.MakeIDSource(ids, elemType)
2367 # Get informations about mesh contents:
2368 # ------------------------------------
2370 ## Get the mesh stattistic
2371 # @return dictionary type element - count of elements
2372 # @ingroup l1_meshinfo
2373 def GetMeshInfo(self, obj = None):
2374 if not obj: obj = self.mesh
2375 return self.smeshpyD.GetMeshInfo(obj)
2377 ## Return the number of nodes in the mesh
2378 # @return an integer value
2379 # @ingroup l1_meshinfo
2381 return self.mesh.NbNodes()
2383 ## Return the number of elements in the mesh
2384 # @return an integer value
2385 # @ingroup l1_meshinfo
2386 def NbElements(self):
2387 return self.mesh.NbElements()
2389 ## Return the number of 0d elements in the mesh
2390 # @return an integer value
2391 # @ingroup l1_meshinfo
2392 def Nb0DElements(self):
2393 return self.mesh.Nb0DElements()
2395 ## Return the number of ball discrete elements in the mesh
2396 # @return an integer value
2397 # @ingroup l1_meshinfo
2399 return self.mesh.NbBalls()
2401 ## Return the number of edges in the mesh
2402 # @return an integer value
2403 # @ingroup l1_meshinfo
2405 return self.mesh.NbEdges()
2407 ## Return the number of edges with the given order in the mesh
2408 # @param elementOrder the order of elements:
2409 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2410 # @return an integer value
2411 # @ingroup l1_meshinfo
2412 def NbEdgesOfOrder(self, elementOrder):
2413 return self.mesh.NbEdgesOfOrder(elementOrder)
2415 ## Return the number of faces in the mesh
2416 # @return an integer value
2417 # @ingroup l1_meshinfo
2419 return self.mesh.NbFaces()
2421 ## Return the number of faces with the given order in the mesh
2422 # @param elementOrder the order of elements:
2423 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2424 # @return an integer value
2425 # @ingroup l1_meshinfo
2426 def NbFacesOfOrder(self, elementOrder):
2427 return self.mesh.NbFacesOfOrder(elementOrder)
2429 ## Return the number of triangles in the mesh
2430 # @return an integer value
2431 # @ingroup l1_meshinfo
2432 def NbTriangles(self):
2433 return self.mesh.NbTriangles()
2435 ## Return the number of triangles with the given order in the mesh
2436 # @param elementOrder is the order of elements:
2437 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2438 # @return an integer value
2439 # @ingroup l1_meshinfo
2440 def NbTrianglesOfOrder(self, elementOrder):
2441 return self.mesh.NbTrianglesOfOrder(elementOrder)
2443 ## Return the number of biquadratic triangles in the mesh
2444 # @return an integer value
2445 # @ingroup l1_meshinfo
2446 def NbBiQuadTriangles(self):
2447 return self.mesh.NbBiQuadTriangles()
2449 ## Return the number of quadrangles in the mesh
2450 # @return an integer value
2451 # @ingroup l1_meshinfo
2452 def NbQuadrangles(self):
2453 return self.mesh.NbQuadrangles()
2455 ## Return the number of quadrangles with the given order in the mesh
2456 # @param elementOrder the order of elements:
2457 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2458 # @return an integer value
2459 # @ingroup l1_meshinfo
2460 def NbQuadranglesOfOrder(self, elementOrder):
2461 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2463 ## Return the number of biquadratic quadrangles in the mesh
2464 # @return an integer value
2465 # @ingroup l1_meshinfo
2466 def NbBiQuadQuadrangles(self):
2467 return self.mesh.NbBiQuadQuadrangles()
2469 ## Return the number of polygons of given order in the mesh
2470 # @param elementOrder the order of elements:
2471 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2472 # @return an integer value
2473 # @ingroup l1_meshinfo
2474 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2475 return self.mesh.NbPolygonsOfOrder(elementOrder)
2477 ## Return the number of volumes in the mesh
2478 # @return an integer value
2479 # @ingroup l1_meshinfo
2480 def NbVolumes(self):
2481 return self.mesh.NbVolumes()
2483 ## Return the number of volumes with the given order in the mesh
2484 # @param elementOrder the order of elements:
2485 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2486 # @return an integer value
2487 # @ingroup l1_meshinfo
2488 def NbVolumesOfOrder(self, elementOrder):
2489 return self.mesh.NbVolumesOfOrder(elementOrder)
2491 ## Return the number of tetrahedrons in the mesh
2492 # @return an integer value
2493 # @ingroup l1_meshinfo
2495 return self.mesh.NbTetras()
2497 ## Return the number of tetrahedrons with the given order in the mesh
2498 # @param elementOrder the order of elements:
2499 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2500 # @return an integer value
2501 # @ingroup l1_meshinfo
2502 def NbTetrasOfOrder(self, elementOrder):
2503 return self.mesh.NbTetrasOfOrder(elementOrder)
2505 ## Return the number of hexahedrons in the mesh
2506 # @return an integer value
2507 # @ingroup l1_meshinfo
2509 return self.mesh.NbHexas()
2511 ## Return the number of hexahedrons with the given order in the mesh
2512 # @param elementOrder the order of elements:
2513 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2514 # @return an integer value
2515 # @ingroup l1_meshinfo
2516 def NbHexasOfOrder(self, elementOrder):
2517 return self.mesh.NbHexasOfOrder(elementOrder)
2519 ## Return the number of triquadratic hexahedrons in the mesh
2520 # @return an integer value
2521 # @ingroup l1_meshinfo
2522 def NbTriQuadraticHexas(self):
2523 return self.mesh.NbTriQuadraticHexas()
2525 ## Return the number of pyramids in the mesh
2526 # @return an integer value
2527 # @ingroup l1_meshinfo
2528 def NbPyramids(self):
2529 return self.mesh.NbPyramids()
2531 ## Return the number of pyramids with the given order in the mesh
2532 # @param elementOrder the order of elements:
2533 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2534 # @return an integer value
2535 # @ingroup l1_meshinfo
2536 def NbPyramidsOfOrder(self, elementOrder):
2537 return self.mesh.NbPyramidsOfOrder(elementOrder)
2539 ## Return the number of prisms in the mesh
2540 # @return an integer value
2541 # @ingroup l1_meshinfo
2543 return self.mesh.NbPrisms()
2545 ## Return the number of prisms with the given order in the mesh
2546 # @param elementOrder the order of elements:
2547 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2548 # @return an integer value
2549 # @ingroup l1_meshinfo
2550 def NbPrismsOfOrder(self, elementOrder):
2551 return self.mesh.NbPrismsOfOrder(elementOrder)
2553 ## Return the number of hexagonal prisms in the mesh
2554 # @return an integer value
2555 # @ingroup l1_meshinfo
2556 def NbHexagonalPrisms(self):
2557 return self.mesh.NbHexagonalPrisms()
2559 ## Return the number of polyhedrons in the mesh
2560 # @return an integer value
2561 # @ingroup l1_meshinfo
2562 def NbPolyhedrons(self):
2563 return self.mesh.NbPolyhedrons()
2565 ## Return the number of submeshes in the mesh
2566 # @return an integer value
2567 # @ingroup l1_meshinfo
2568 def NbSubMesh(self):
2569 return self.mesh.NbSubMesh()
2571 ## Return the list of mesh elements IDs
2572 # @return the list of integer values
2573 # @ingroup l1_meshinfo
2574 def GetElementsId(self):
2575 return self.mesh.GetElementsId()
2577 ## Return the list of IDs of mesh elements with the given type
2578 # @param elementType the required type of elements, either of
2579 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2580 # @return list of integer values
2581 # @ingroup l1_meshinfo
2582 def GetElementsByType(self, elementType):
2583 return self.mesh.GetElementsByType(elementType)
2585 ## Return the list of mesh nodes IDs
2586 # @return the list of integer values
2587 # @ingroup l1_meshinfo
2588 def GetNodesId(self):
2589 return self.mesh.GetNodesId()
2591 # Get the information about mesh elements:
2592 # ------------------------------------
2594 ## Return the type of mesh element
2595 # @return the value from SMESH::ElementType enumeration
2596 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2597 # @ingroup l1_meshinfo
2598 def GetElementType(self, id, iselem=True):
2599 return self.mesh.GetElementType(id, iselem)
2601 ## Return the geometric type of mesh element
2602 # @return the value from SMESH::EntityType enumeration
2603 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2604 # @ingroup l1_meshinfo
2605 def GetElementGeomType(self, id):
2606 return self.mesh.GetElementGeomType(id)
2608 ## Return the shape type of mesh element
2609 # @return the value from SMESH::GeometryType enumeration.
2610 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2611 # @ingroup l1_meshinfo
2612 def GetElementShape(self, id):
2613 return self.mesh.GetElementShape(id)
2615 ## Return the list of submesh elements IDs
2616 # @param Shape a geom object(sub-shape)
2617 # Shape must be the sub-shape of a ShapeToMesh()
2618 # @return the list of integer values
2619 # @ingroup l1_meshinfo
2620 def GetSubMeshElementsId(self, Shape):
2621 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2622 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2625 return self.mesh.GetSubMeshElementsId(ShapeID)
2627 ## Return the list of submesh nodes IDs
2628 # @param Shape a geom object(sub-shape)
2629 # Shape must be the sub-shape of a ShapeToMesh()
2630 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2631 # @return the list of integer values
2632 # @ingroup l1_meshinfo
2633 def GetSubMeshNodesId(self, Shape, all):
2634 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2635 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2638 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2640 ## Return type of elements on given shape
2641 # @param Shape a geom object(sub-shape)
2642 # Shape must be a sub-shape of a ShapeToMesh()
2643 # @return element type
2644 # @ingroup l1_meshinfo
2645 def GetSubMeshElementType(self, Shape):
2646 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2647 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2650 return self.mesh.GetSubMeshElementType(ShapeID)
2652 ## Get the mesh description
2653 # @return string value
2654 # @ingroup l1_meshinfo
2656 return self.mesh.Dump()
2659 # Get the information about nodes and elements of a mesh by its IDs:
2660 # -----------------------------------------------------------
2662 ## Get XYZ coordinates of a node
2663 # \n If there is no nodes for the given ID - return an empty list
2664 # @return a list of double precision values
2665 # @ingroup l1_meshinfo
2666 def GetNodeXYZ(self, id):
2667 return self.mesh.GetNodeXYZ(id)
2669 ## Return list of IDs of inverse elements for the given node
2670 # \n If there is no node for the given ID - return an empty list
2671 # @return a list of integer values
2672 # @ingroup l1_meshinfo
2673 def GetNodeInverseElements(self, id):
2674 return self.mesh.GetNodeInverseElements(id)
2676 ## Return the position of a node on the shape
2677 # @return SMESH::NodePosition
2678 # @ingroup l1_meshinfo
2679 def GetNodePosition(self,NodeID):
2680 return self.mesh.GetNodePosition(NodeID)
2682 ## Return the position of an element on the shape
2683 # @return SMESH::ElementPosition
2684 # @ingroup l1_meshinfo
2685 def GetElementPosition(self,ElemID):
2686 return self.mesh.GetElementPosition(ElemID)
2688 ## Return the ID of the shape, on which the given node was generated.
2689 # @return an integer value > 0 or -1 if there is no node for the given
2690 # ID or the node is not assigned to any geometry
2691 # @ingroup l1_meshinfo
2692 def GetShapeID(self, id):
2693 return self.mesh.GetShapeID(id)
2695 ## Return the ID of the shape, on which the given element was generated.
2696 # @return an integer value > 0 or -1 if there is no element for the given
2697 # ID or the element is not assigned to any geometry
2698 # @ingroup l1_meshinfo
2699 def GetShapeIDForElem(self,id):
2700 return self.mesh.GetShapeIDForElem(id)
2702 ## Return the number of nodes of the given element
2703 # @return an integer value > 0 or -1 if there is no element for the given ID
2704 # @ingroup l1_meshinfo
2705 def GetElemNbNodes(self, id):
2706 return self.mesh.GetElemNbNodes(id)
2708 ## Return the node ID the given (zero based) index for the given element
2709 # \n If there is no element for the given ID - return -1
2710 # \n If there is no node for the given index - return -2
2711 # @return an integer value
2712 # @ingroup l1_meshinfo
2713 def GetElemNode(self, id, index):
2714 return self.mesh.GetElemNode(id, index)
2716 ## Return the IDs of nodes of the given element
2717 # @return a list of integer values
2718 # @ingroup l1_meshinfo
2719 def GetElemNodes(self, id):
2720 return self.mesh.GetElemNodes(id)
2722 ## Return true if the given node is the medium node in the given quadratic element
2723 # @ingroup l1_meshinfo
2724 def IsMediumNode(self, elementID, nodeID):
2725 return self.mesh.IsMediumNode(elementID, nodeID)
2727 ## Return true if the given node is the medium node in one of quadratic elements
2728 # @param nodeID ID of the node
2729 # @param elementType the type of elements to check a state of the node, either of
2730 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2731 # @ingroup l1_meshinfo
2732 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2733 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2735 ## Return the number of edges for the given element
2736 # @ingroup l1_meshinfo
2737 def ElemNbEdges(self, id):
2738 return self.mesh.ElemNbEdges(id)
2740 ## Return the number of faces for the given element
2741 # @ingroup l1_meshinfo
2742 def ElemNbFaces(self, id):
2743 return self.mesh.ElemNbFaces(id)
2745 ## Return nodes of given face (counted from zero) for given volumic element.
2746 # @ingroup l1_meshinfo
2747 def GetElemFaceNodes(self,elemId, faceIndex):
2748 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2750 ## Return three components of normal of given mesh face
2751 # (or an empty array in KO case)
2752 # @ingroup l1_meshinfo
2753 def GetFaceNormal(self, faceId, normalized=False):
2754 return self.mesh.GetFaceNormal(faceId,normalized)
2756 ## Return an element based on all given nodes.
2757 # @ingroup l1_meshinfo
2758 def FindElementByNodes(self,nodes):
2759 return self.mesh.FindElementByNodes(nodes)
2761 ## Return true if the given element is a polygon
2762 # @ingroup l1_meshinfo
2763 def IsPoly(self, id):
2764 return self.mesh.IsPoly(id)
2766 ## Return true if the given element is quadratic
2767 # @ingroup l1_meshinfo
2768 def IsQuadratic(self, id):
2769 return self.mesh.IsQuadratic(id)
2771 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2772 # @ingroup l1_meshinfo
2773 def GetBallDiameter(self, id):
2774 return self.mesh.GetBallDiameter(id)
2776 ## Return XYZ coordinates of the barycenter of the given element
2777 # \n If there is no element for the given ID - return an empty list
2778 # @return a list of three double values
2779 # @ingroup l1_meshinfo
2780 def BaryCenter(self, id):
2781 return self.mesh.BaryCenter(id)
2783 ## Pass mesh elements through the given filter and return IDs of fitting elements
2784 # @param theFilter SMESH_Filter
2785 # @return a list of ids
2786 # @ingroup l1_controls
2787 def GetIdsFromFilter(self, theFilter):
2788 theFilter.SetMesh( self.mesh )
2789 return theFilter.GetIDs()
2791 # Get mesh measurements information:
2792 # ------------------------------------
2794 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2795 # Return a list of special structures (borders).
2796 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2797 # @ingroup l1_measurements
2798 def GetFreeBorders(self):
2799 aFilterMgr = self.smeshpyD.CreateFilterManager()
2800 aPredicate = aFilterMgr.CreateFreeEdges()
2801 aPredicate.SetMesh(self.mesh)
2802 aBorders = aPredicate.GetBorders()
2803 aFilterMgr.UnRegister()
2806 ## Get minimum distance between two nodes, elements or distance to the origin
2807 # @param id1 first node/element id
2808 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2809 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2810 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2811 # @return minimum distance value
2812 # @sa GetMinDistance()
2813 # @ingroup l1_measurements
2814 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2815 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2816 return aMeasure.value
2818 ## Get measure structure specifying minimum distance data between two objects
2819 # @param id1 first node/element id
2820 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2821 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2822 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2823 # @return Measure structure
2825 # @ingroup l1_measurements
2826 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2828 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2830 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2833 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2835 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2840 aMeasurements = self.smeshpyD.CreateMeasurements()
2841 aMeasure = aMeasurements.MinDistance(id1, id2)
2842 genObjUnRegister([aMeasurements,id1, id2])
2845 ## Get bounding box of the specified object(s)
2846 # @param objects single source object or list of source objects or list of nodes/elements IDs
2847 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2848 # @c False specifies that @a objects are nodes
2849 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2850 # @sa GetBoundingBox()
2851 # @ingroup l1_measurements
2852 def BoundingBox(self, objects=None, isElem=False):
2853 result = self.GetBoundingBox(objects, isElem)
2857 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2860 ## Get measure structure specifying bounding box data of the specified object(s)
2861 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2862 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2863 # @c False specifies that @a objects are nodes
2864 # @return Measure structure
2866 # @ingroup l1_measurements
2867 def GetBoundingBox(self, IDs=None, isElem=False):
2870 elif isinstance(IDs, tuple):
2872 if not isinstance(IDs, list):
2874 if len(IDs) > 0 and isinstance(IDs[0], int):
2877 unRegister = genObjUnRegister()
2879 if isinstance(o, Mesh):
2880 srclist.append(o.mesh)
2881 elif hasattr(o, "_narrow"):
2882 src = o._narrow(SMESH.SMESH_IDSource)
2883 if src: srclist.append(src)
2885 elif isinstance(o, list):
2887 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2889 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2890 unRegister.set( srclist[-1] )
2893 aMeasurements = self.smeshpyD.CreateMeasurements()
2894 unRegister.set( aMeasurements )
2895 aMeasure = aMeasurements.BoundingBox(srclist)
2898 # Mesh edition (SMESH_MeshEditor functionality):
2899 # ---------------------------------------------
2901 ## Remove the elements from the mesh by ids
2902 # @param IDsOfElements is a list of ids of elements to remove
2903 # @return True or False
2904 # @ingroup l2_modif_del
2905 def RemoveElements(self, IDsOfElements):
2906 return self.editor.RemoveElements(IDsOfElements)
2908 ## Remove nodes from mesh by ids
2909 # @param IDsOfNodes is a list of ids of nodes to remove
2910 # @return True or False
2911 # @ingroup l2_modif_del
2912 def RemoveNodes(self, IDsOfNodes):
2913 return self.editor.RemoveNodes(IDsOfNodes)
2915 ## Remove all orphan (free) nodes from mesh
2916 # @return number of the removed nodes
2917 # @ingroup l2_modif_del
2918 def RemoveOrphanNodes(self):
2919 return self.editor.RemoveOrphanNodes()
2921 ## Add a node to the mesh by coordinates
2922 # @return Id of the new node
2923 # @ingroup l2_modif_add
2924 def AddNode(self, x, y, z):
2925 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2926 if hasVars: self.mesh.SetParameters(Parameters)
2927 return self.editor.AddNode( x, y, z)
2929 ## Create a 0D element on a node with given number.
2930 # @param IDOfNode the ID of node for creation of the element.
2931 # @param DuplicateElements to add one more 0D element to a node or not
2932 # @return the Id of the new 0D element
2933 # @ingroup l2_modif_add
2934 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2935 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2937 ## Create 0D elements on all nodes of the given elements except those
2938 # nodes on which a 0D element already exists.
2939 # @param theObject an object on whose nodes 0D elements will be created.
2940 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2941 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2942 # @param theGroupName optional name of a group to add 0D elements created
2943 # and/or found on nodes of \a theObject.
2944 # @param DuplicateElements to add one more 0D element to a node or not
2945 # @return an object (a new group or a temporary SMESH_IDSource) holding
2946 # IDs of new and/or found 0D elements. IDs of 0D elements
2947 # can be retrieved from the returned object by calling GetIDs()
2948 # @ingroup l2_modif_add
2949 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2950 unRegister = genObjUnRegister()
2951 if isinstance( theObject, Mesh ):
2952 theObject = theObject.GetMesh()
2953 elif isinstance( theObject, list ):
2954 theObject = self.GetIDSource( theObject, SMESH.ALL )
2955 unRegister.set( theObject )
2956 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2958 ## Create a ball element on a node with given ID.
2959 # @param IDOfNode the ID of node for creation of the element.
2960 # @param diameter the bal diameter.
2961 # @return the Id of the new ball element
2962 # @ingroup l2_modif_add
2963 def AddBall(self, IDOfNode, diameter):
2964 return self.editor.AddBall( IDOfNode, diameter )
2966 ## Create a linear or quadratic edge (this is determined
2967 # by the number of given nodes).
2968 # @param IDsOfNodes the list of node IDs for creation of the element.
2969 # The order of nodes in this list should correspond to the description
2970 # of MED. \n This description is located by the following link:
2971 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2972 # @return the Id of the new edge
2973 # @ingroup l2_modif_add
2974 def AddEdge(self, IDsOfNodes):
2975 return self.editor.AddEdge(IDsOfNodes)
2977 ## Create a linear or quadratic face (this is determined
2978 # by the number of given nodes).
2979 # @param IDsOfNodes the list of node IDs for creation of the element.
2980 # The order of nodes in this list should correspond to the description
2981 # of MED. \n This description is located by the following link:
2982 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2983 # @return the Id of the new face
2984 # @ingroup l2_modif_add
2985 def AddFace(self, IDsOfNodes):
2986 return self.editor.AddFace(IDsOfNodes)
2988 ## Add a polygonal face to the mesh by the list of node IDs
2989 # @param IdsOfNodes the list of node IDs for creation of the element.
2990 # @return the Id of the new face
2991 # @ingroup l2_modif_add
2992 def AddPolygonalFace(self, IdsOfNodes):
2993 return self.editor.AddPolygonalFace(IdsOfNodes)
2995 ## Add a quadratic polygonal face to the mesh by the list of node IDs
2996 # @param IdsOfNodes the list of node IDs for creation of the element;
2997 # corner nodes follow first.
2998 # @return the Id of the new face
2999 # @ingroup l2_modif_add
3000 def AddQuadPolygonalFace(self, IdsOfNodes):
3001 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3003 ## Create both simple and quadratic volume (this is determined
3004 # by the number of given nodes).
3005 # @param IDsOfNodes the list of node IDs for creation of the element.
3006 # The order of nodes in this list should correspond to the description
3007 # of MED. \n This description is located by the following link:
3008 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3009 # @return the Id of the new volumic element
3010 # @ingroup l2_modif_add
3011 def AddVolume(self, IDsOfNodes):
3012 return self.editor.AddVolume(IDsOfNodes)
3014 ## Create a volume of many faces, giving nodes for each face.
3015 # @param IdsOfNodes the list of node IDs for volume creation face by face.
3016 # @param Quantities the list of integer values, Quantities[i]
3017 # gives the quantity of nodes in face number i.
3018 # @return the Id of the new volumic element
3019 # @ingroup l2_modif_add
3020 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3021 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3023 ## Create a volume of many faces, giving the IDs of the existing faces.
3024 # @param IdsOfFaces the list of face IDs for volume creation.
3026 # Note: The created volume will refer only to the nodes
3027 # of the given faces, not to the faces themselves.
3028 # @return the Id of the new volumic element
3029 # @ingroup l2_modif_add
3030 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3031 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3034 ## @brief Binds a node to a vertex
3035 # @param NodeID a node ID
3036 # @param Vertex a vertex or vertex ID
3037 # @return True if succeed else raises an exception
3038 # @ingroup l2_modif_add
3039 def SetNodeOnVertex(self, NodeID, Vertex):
3040 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3041 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3045 self.editor.SetNodeOnVertex(NodeID, VertexID)
3046 except SALOME.SALOME_Exception as inst:
3047 raise ValueError(inst.details.text)
3051 ## @brief Stores the node position on an edge
3052 # @param NodeID a node ID
3053 # @param Edge an edge or edge ID
3054 # @param paramOnEdge a parameter on the edge where the node is located
3055 # @return True if succeed else raises an exception
3056 # @ingroup l2_modif_add
3057 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3058 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3059 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3063 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3064 except SALOME.SALOME_Exception as inst:
3065 raise ValueError(inst.details.text)
3068 ## @brief Stores node position on a face
3069 # @param NodeID a node ID
3070 # @param Face a face or face ID
3071 # @param u U parameter on the face where the node is located
3072 # @param v V parameter on the face where the node is located
3073 # @return True if succeed else raises an exception
3074 # @ingroup l2_modif_add
3075 def SetNodeOnFace(self, NodeID, Face, u, v):
3076 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3077 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3081 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3082 except SALOME.SALOME_Exception as inst:
3083 raise ValueError(inst.details.text)
3086 ## @brief Binds a node to a solid
3087 # @param NodeID a node ID
3088 # @param Solid a solid or solid ID
3089 # @return True if succeed else raises an exception
3090 # @ingroup l2_modif_add
3091 def SetNodeInVolume(self, NodeID, Solid):
3092 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3093 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3097 self.editor.SetNodeInVolume(NodeID, SolidID)
3098 except SALOME.SALOME_Exception as inst:
3099 raise ValueError(inst.details.text)
3102 ## @brief Bind an element to a shape
3103 # @param ElementID an element ID
3104 # @param Shape a shape or shape ID
3105 # @return True if succeed else raises an exception
3106 # @ingroup l2_modif_add
3107 def SetMeshElementOnShape(self, ElementID, Shape):
3108 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3109 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3113 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3114 except SALOME.SALOME_Exception as inst:
3115 raise ValueError(inst.details.text)
3119 ## Move the node with the given id
3120 # @param NodeID the id of the node
3121 # @param x a new X coordinate
3122 # @param y a new Y coordinate
3123 # @param z a new Z coordinate
3124 # @return True if succeed else False
3125 # @ingroup l2_modif_edit
3126 def MoveNode(self, NodeID, x, y, z):
3127 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3128 if hasVars: self.mesh.SetParameters(Parameters)
3129 return self.editor.MoveNode(NodeID, x, y, z)
3131 ## Find the node closest to a point and moves it to a point location
3132 # @param x the X coordinate of a point
3133 # @param y the Y coordinate of a point
3134 # @param z the Z coordinate of a point
3135 # @param NodeID if specified (>0), the node with this ID is moved,
3136 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3137 # @return the ID of a node
3138 # @ingroup l2_modif_edit
3139 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3140 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3141 if hasVars: self.mesh.SetParameters(Parameters)
3142 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3144 ## Find the node closest to a point
3145 # @param x the X coordinate of a point
3146 # @param y the Y coordinate of a point
3147 # @param z the Z coordinate of a point
3148 # @return the ID of a node
3149 # @ingroup l1_meshinfo
3150 def FindNodeClosestTo(self, x, y, z):
3151 #preview = self.mesh.GetMeshEditPreviewer()
3152 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3153 return self.editor.FindNodeClosestTo(x, y, z)
3155 ## Find the elements where a point lays IN or ON
3156 # @param x the X coordinate of a point
3157 # @param y the Y coordinate of a point
3158 # @param z the Z coordinate of a point
3159 # @param elementType type of elements to find; either of
3160 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3161 # means elements of any type excluding nodes, discrete and 0D elements.
3162 # @param meshPart a part of mesh (group, sub-mesh) to search within
3163 # @return list of IDs of found elements
3164 # @ingroup l1_meshinfo
3165 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3167 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3169 return self.editor.FindElementsByPoint(x, y, z, elementType)
3171 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3172 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3173 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3174 # @ingroup l1_meshinfo
3175 def GetPointState(self, x, y, z):
3176 return self.editor.GetPointState(x, y, z)
3178 ## Find the node closest to a point and moves it to a point location
3179 # @param x the X coordinate of a point
3180 # @param y the Y coordinate of a point
3181 # @param z the Z coordinate of a point
3182 # @return the ID of a moved node
3183 # @ingroup l2_modif_edit
3184 def MeshToPassThroughAPoint(self, x, y, z):
3185 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3187 ## Replace two neighbour triangles sharing Node1-Node2 link
3188 # with the triangles built on the same 4 nodes but having other common link.
3189 # @param NodeID1 the ID of the first node
3190 # @param NodeID2 the ID of the second node
3191 # @return false if proper faces were not found
3192 # @ingroup l2_modif_cutquadr
3193 def InverseDiag(self, NodeID1, NodeID2):
3194 return self.editor.InverseDiag(NodeID1, NodeID2)
3196 ## Replace two neighbour triangles sharing Node1-Node2 link
3197 # with a quadrangle built on the same 4 nodes.
3198 # @param NodeID1 the ID of the first node
3199 # @param NodeID2 the ID of the second node
3200 # @return false if proper faces were not found
3201 # @ingroup l2_modif_unitetri
3202 def DeleteDiag(self, NodeID1, NodeID2):
3203 return self.editor.DeleteDiag(NodeID1, NodeID2)
3205 ## Reorient elements by ids
3206 # @param IDsOfElements if undefined reorients all mesh elements
3207 # @return True if succeed else False
3208 # @ingroup l2_modif_changori
3209 def Reorient(self, IDsOfElements=None):
3210 if IDsOfElements == None:
3211 IDsOfElements = self.GetElementsId()
3212 return self.editor.Reorient(IDsOfElements)
3214 ## Reorient all elements of the object
3215 # @param theObject mesh, submesh or group
3216 # @return True if succeed else False
3217 # @ingroup l2_modif_changori
3218 def ReorientObject(self, theObject):
3219 if ( isinstance( theObject, Mesh )):
3220 theObject = theObject.GetMesh()
3221 return self.editor.ReorientObject(theObject)
3223 ## Reorient faces contained in \a the2DObject.
3224 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3225 # @param theDirection is a desired direction of normal of \a theFace.
3226 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3227 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3228 # compared with theDirection. It can be either ID of face or a point
3229 # by which the face will be found. The point can be given as either
3230 # a GEOM vertex or a list of point coordinates.
3231 # @return number of reoriented faces
3232 # @ingroup l2_modif_changori
3233 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3234 unRegister = genObjUnRegister()
3236 if isinstance( the2DObject, Mesh ):
3237 the2DObject = the2DObject.GetMesh()
3238 if isinstance( the2DObject, list ):
3239 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3240 unRegister.set( the2DObject )
3241 # check theDirection
3242 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3243 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3244 if isinstance( theDirection, list ):
3245 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3246 # prepare theFace and thePoint
3247 theFace = theFaceOrPoint
3248 thePoint = PointStruct(0,0,0)
3249 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3250 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3252 if isinstance( theFaceOrPoint, list ):
3253 thePoint = PointStruct( *theFaceOrPoint )
3255 if isinstance( theFaceOrPoint, PointStruct ):
3256 thePoint = theFaceOrPoint
3258 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3260 ## Reorient faces according to adjacent volumes.
3261 # @param the2DObject is a mesh, sub-mesh, group or list of
3262 # either IDs of faces or face groups.
3263 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3264 # @param theOutsideNormal to orient faces to have their normals
3265 # pointing either \a outside or \a inside the adjacent volumes.
3266 # @return number of reoriented faces.
3267 # @ingroup l2_modif_changori
3268 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3269 unRegister = genObjUnRegister()
3271 if not isinstance( the2DObject, list ):
3272 the2DObject = [ the2DObject ]
3273 elif the2DObject and isinstance( the2DObject[0], int ):
3274 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3275 unRegister.set( the2DObject )
3276 the2DObject = [ the2DObject ]
3277 for i,obj2D in enumerate( the2DObject ):
3278 if isinstance( obj2D, Mesh ):
3279 the2DObject[i] = obj2D.GetMesh()
3280 if isinstance( obj2D, list ):
3281 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3282 unRegister.set( the2DObject[i] )
3284 if isinstance( the3DObject, Mesh ):
3285 the3DObject = the3DObject.GetMesh()
3286 if isinstance( the3DObject, list ):
3287 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3288 unRegister.set( the3DObject )
3289 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3291 ## Fuse the neighbouring triangles into quadrangles.
3292 # @param IDsOfElements The triangles to be fused.
3293 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3294 # applied to possible quadrangles to choose a neighbour to fuse with.
3295 # Type SMESH.FunctorType._items in the Python Console to see all items.
3296 # Note that not all items correspond to numerical functors.
3297 # @param MaxAngle is the maximum angle between element normals at which the fusion
3298 # is still performed; theMaxAngle is mesured in radians.
3299 # Also it could be a name of variable which defines angle in degrees.
3300 # @return TRUE in case of success, FALSE otherwise.
3301 # @ingroup l2_modif_unitetri
3302 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3303 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3304 self.mesh.SetParameters(Parameters)
3305 if not IDsOfElements:
3306 IDsOfElements = self.GetElementsId()
3307 Functor = self.smeshpyD.GetFunctor(theCriterion)
3308 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3310 ## Fuse the neighbouring triangles of the object into quadrangles
3311 # @param theObject is mesh, submesh or group
3312 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3313 # applied to possible quadrangles to choose a neighbour to fuse with.
3314 # Type SMESH.FunctorType._items in the Python Console to see all items.
3315 # Note that not all items correspond to numerical functors.
3316 # @param MaxAngle a max angle between element normals at which the fusion
3317 # is still performed; theMaxAngle is mesured in radians.
3318 # @return TRUE in case of success, FALSE otherwise.
3319 # @ingroup l2_modif_unitetri
3320 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3321 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3322 self.mesh.SetParameters(Parameters)
3323 if isinstance( theObject, Mesh ):
3324 theObject = theObject.GetMesh()
3325 Functor = self.smeshpyD.GetFunctor(theCriterion)
3326 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3328 ## Split quadrangles into triangles.
3329 # @param IDsOfElements the faces to be splitted.
3330 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3331 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3332 # value, then quadrangles will be split by the smallest diagonal.
3333 # Type SMESH.FunctorType._items in the Python Console to see all items.
3334 # Note that not all items correspond to numerical functors.
3335 # @return TRUE in case of success, FALSE otherwise.
3336 # @ingroup l2_modif_cutquadr
3337 def QuadToTri (self, IDsOfElements, theCriterion = None):
3338 if IDsOfElements == []:
3339 IDsOfElements = self.GetElementsId()
3340 if theCriterion is None:
3341 theCriterion = FT_MaxElementLength2D
3342 Functor = self.smeshpyD.GetFunctor(theCriterion)
3343 return self.editor.QuadToTri(IDsOfElements, Functor)
3345 ## Split quadrangles into triangles.
3346 # @param theObject the object from which the list of elements is taken,
3347 # this is mesh, submesh or group
3348 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3349 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3350 # value, then quadrangles will be split by the smallest diagonal.
3351 # Type SMESH.FunctorType._items in the Python Console to see all items.
3352 # Note that not all items correspond to numerical functors.
3353 # @return TRUE in case of success, FALSE otherwise.
3354 # @ingroup l2_modif_cutquadr
3355 def QuadToTriObject (self, theObject, theCriterion = None):
3356 if ( isinstance( theObject, Mesh )):
3357 theObject = theObject.GetMesh()
3358 if theCriterion is None:
3359 theCriterion = FT_MaxElementLength2D
3360 Functor = self.smeshpyD.GetFunctor(theCriterion)
3361 return self.editor.QuadToTriObject(theObject, Functor)
3363 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3365 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3366 # group or a list of face IDs. By default all quadrangles are split
3367 # @ingroup l2_modif_cutquadr
3368 def QuadTo4Tri (self, theElements=[]):
3369 unRegister = genObjUnRegister()
3370 if isinstance( theElements, Mesh ):
3371 theElements = theElements.mesh
3372 elif not theElements:
3373 theElements = self.mesh
3374 elif isinstance( theElements, list ):
3375 theElements = self.GetIDSource( theElements, SMESH.FACE )
3376 unRegister.set( theElements )
3377 return self.editor.QuadTo4Tri( theElements )
3379 ## Split quadrangles into triangles.
3380 # @param IDsOfElements the faces to be splitted
3381 # @param Diag13 is used to choose a diagonal for splitting.
3382 # @return TRUE in case of success, FALSE otherwise.
3383 # @ingroup l2_modif_cutquadr
3384 def SplitQuad (self, IDsOfElements, Diag13):
3385 if IDsOfElements == []:
3386 IDsOfElements = self.GetElementsId()
3387 return self.editor.SplitQuad(IDsOfElements, Diag13)
3389 ## Split quadrangles into triangles.
3390 # @param theObject the object from which the list of elements is taken,
3391 # this is mesh, submesh or group
3392 # @param Diag13 is used to choose a diagonal for splitting.
3393 # @return TRUE in case of success, FALSE otherwise.
3394 # @ingroup l2_modif_cutquadr
3395 def SplitQuadObject (self, theObject, Diag13):
3396 if ( isinstance( theObject, Mesh )):
3397 theObject = theObject.GetMesh()
3398 return self.editor.SplitQuadObject(theObject, Diag13)
3400 ## Find a better splitting of the given quadrangle.
3401 # @param IDOfQuad the ID of the quadrangle to be splitted.
3402 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3403 # choose a diagonal for splitting.
3404 # Type SMESH.FunctorType._items in the Python Console to see all items.
3405 # Note that not all items correspond to numerical functors.
3406 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3407 # diagonal is better, 0 if error occurs.
3408 # @ingroup l2_modif_cutquadr
3409 def BestSplit (self, IDOfQuad, theCriterion):
3410 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3412 ## Split volumic elements into tetrahedrons
3413 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3414 # @param method flags passing splitting method:
3415 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3416 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3417 # @ingroup l2_modif_cutquadr
3418 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3419 unRegister = genObjUnRegister()
3420 if isinstance( elems, Mesh ):
3421 elems = elems.GetMesh()
3422 if ( isinstance( elems, list )):
3423 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3424 unRegister.set( elems )
3425 self.editor.SplitVolumesIntoTetra(elems, method)
3428 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3429 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3430 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3431 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3432 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3433 # will be split in order to keep the mesh conformal.
3434 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3435 # if None (default), all bi-quadratic elements will be split
3436 # @ingroup l2_modif_cutquadr
3437 def SplitBiQuadraticIntoLinear(self, elems=None):
3438 unRegister = genObjUnRegister()
3439 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3440 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3441 unRegister.set( elems )
3443 elems = [ self.GetMesh() ]
3444 if isinstance( elems, Mesh ):
3445 elems = [ elems.GetMesh() ]
3446 if not isinstance( elems, list ):
3448 self.editor.SplitBiQuadraticIntoLinear( elems )
3450 ## Split hexahedra into prisms
3451 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3452 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3453 # gives a normal vector defining facets to split into triangles.
3454 # @a startHexPoint can be either a triple of coordinates or a vertex.
3455 # @param facetNormal a normal to a facet to split into triangles of a
3456 # hexahedron found by @a startHexPoint.
3457 # @a facetNormal can be either a triple of coordinates or an edge.
3458 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3459 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3460 # @param allDomains if @c False, only hexahedra adjacent to one closest
3461 # to @a startHexPoint are split, else @a startHexPoint
3462 # is used to find the facet to split in all domains present in @a elems.
3463 # @ingroup l2_modif_cutquadr
3464 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3465 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3467 unRegister = genObjUnRegister()
3468 if isinstance( elems, Mesh ):
3469 elems = elems.GetMesh()
3470 if ( isinstance( elems, list )):
3471 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3472 unRegister.set( elems )
3475 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3476 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3477 elif isinstance( startHexPoint, list ):
3478 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3481 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3482 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3483 elif isinstance( facetNormal, list ):
3484 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3487 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3489 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3491 ## Split quadrangle faces near triangular facets of volumes
3493 # @ingroup l2_modif_cutquadr
3494 def SplitQuadsNearTriangularFacets(self):
3495 faces_array = self.GetElementsByType(SMESH.FACE)
3496 for face_id in faces_array:
3497 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3498 quad_nodes = self.mesh.GetElemNodes(face_id)
3499 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3500 isVolumeFound = False
3501 for node1_elem in node1_elems:
3502 if not isVolumeFound:
3503 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3504 nb_nodes = self.GetElemNbNodes(node1_elem)
3505 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3506 volume_elem = node1_elem
3507 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3508 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3509 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3510 isVolumeFound = True
3511 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3512 self.SplitQuad([face_id], False) # diagonal 2-4
3513 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3514 isVolumeFound = True
3515 self.SplitQuad([face_id], True) # diagonal 1-3
3516 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3517 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3518 isVolumeFound = True
3519 self.SplitQuad([face_id], True) # diagonal 1-3
3521 ## @brief Splits hexahedrons into tetrahedrons.
3523 # This operation uses pattern mapping functionality for splitting.
3524 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3525 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3526 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3527 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3528 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3529 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3530 # @return TRUE in case of success, FALSE otherwise.
3531 # @ingroup l2_modif_cutquadr
3532 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3533 # Pattern: 5.---------.6
3538 # (0,0,1) 4.---------.7 * |
3545 # (0,0,0) 0.---------.3
3546 pattern_tetra = "!!! Nb of points: \n 8 \n\
3556 !!! Indices of points of 6 tetras: \n\
3564 pattern = self.smeshpyD.GetPattern()
3565 isDone = pattern.LoadFromFile(pattern_tetra)
3567 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3570 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3571 isDone = pattern.MakeMesh(self.mesh, False, False)
3572 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3574 # split quafrangle faces near triangular facets of volumes
3575 self.SplitQuadsNearTriangularFacets()
3579 ## @brief Split hexahedrons into prisms.
3581 # Uses the pattern mapping functionality for splitting.
3582 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3583 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3584 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3585 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3586 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3587 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3588 # @return TRUE in case of success, FALSE otherwise.
3589 # @ingroup l2_modif_cutquadr
3590 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3591 # Pattern: 5.---------.6
3596 # (0,0,1) 4.---------.7 |
3603 # (0,0,0) 0.---------.3
3604 pattern_prism = "!!! Nb of points: \n 8 \n\
3614 !!! Indices of points of 2 prisms: \n\
3618 pattern = self.smeshpyD.GetPattern()
3619 isDone = pattern.LoadFromFile(pattern_prism)
3621 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3624 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3625 isDone = pattern.MakeMesh(self.mesh, False, False)
3626 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3628 # Split quafrangle faces near triangular facets of volumes
3629 self.SplitQuadsNearTriangularFacets()
3634 # @param IDsOfElements the list if ids of elements to smooth
3635 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3636 # Note that nodes built on edges and boundary nodes are always fixed.
3637 # @param MaxNbOfIterations the maximum number of iterations
3638 # @param MaxAspectRatio varies in range [1.0, inf]
3639 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3640 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3641 # @return TRUE in case of success, FALSE otherwise.
3642 # @ingroup l2_modif_smooth
3643 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3644 MaxNbOfIterations, MaxAspectRatio, Method):
3645 if IDsOfElements == []:
3646 IDsOfElements = self.GetElementsId()
3647 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3648 self.mesh.SetParameters(Parameters)
3649 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3650 MaxNbOfIterations, MaxAspectRatio, Method)
3652 ## Smooth elements which belong to the given object
3653 # @param theObject the object to smooth
3654 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3655 # Note that nodes built on edges and boundary nodes are always fixed.
3656 # @param MaxNbOfIterations the maximum number of iterations
3657 # @param MaxAspectRatio varies in range [1.0, inf]
3658 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3659 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3660 # @return TRUE in case of success, FALSE otherwise.
3661 # @ingroup l2_modif_smooth
3662 def SmoothObject(self, theObject, IDsOfFixedNodes,
3663 MaxNbOfIterations, MaxAspectRatio, Method):
3664 if ( isinstance( theObject, Mesh )):
3665 theObject = theObject.GetMesh()
3666 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3667 MaxNbOfIterations, MaxAspectRatio, Method)
3669 ## Parametrically smooth the given elements
3670 # @param IDsOfElements the list if ids of elements to smooth
3671 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3672 # Note that nodes built on edges and boundary nodes are always fixed.
3673 # @param MaxNbOfIterations the maximum number of iterations
3674 # @param MaxAspectRatio varies in range [1.0, inf]
3675 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3676 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3677 # @return TRUE in case of success, FALSE otherwise.
3678 # @ingroup l2_modif_smooth
3679 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3680 MaxNbOfIterations, MaxAspectRatio, Method):
3681 if IDsOfElements == []:
3682 IDsOfElements = self.GetElementsId()
3683 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3684 self.mesh.SetParameters(Parameters)
3685 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3686 MaxNbOfIterations, MaxAspectRatio, Method)
3688 ## Parametrically smooth the elements which belong to the given object
3689 # @param theObject the object to smooth
3690 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3691 # Note that nodes built on edges and boundary nodes are always fixed.
3692 # @param MaxNbOfIterations the maximum number of iterations
3693 # @param MaxAspectRatio varies in range [1.0, inf]
3694 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3695 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3696 # @return TRUE in case of success, FALSE otherwise.
3697 # @ingroup l2_modif_smooth
3698 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3699 MaxNbOfIterations, MaxAspectRatio, Method):
3700 if ( isinstance( theObject, Mesh )):
3701 theObject = theObject.GetMesh()
3702 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3703 MaxNbOfIterations, MaxAspectRatio, Method)
3705 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3706 # them with quadratic with the same id.
3707 # @param theForce3d new node creation method:
3708 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3709 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3710 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3711 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3712 # @return SMESH.ComputeError which can hold a warning
3713 # @ingroup l2_modif_tofromqu
3714 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3715 if isinstance( theSubMesh, Mesh ):
3716 theSubMesh = theSubMesh.mesh
3718 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3721 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3723 self.editor.ConvertToQuadratic(theForce3d)
3724 error = self.editor.GetLastError()
3725 if error and error.comment:
3726 print(error.comment)
3729 ## Convert the mesh from quadratic to ordinary,
3730 # deletes old quadratic elements, \n replacing
3731 # them with ordinary mesh elements with the same id.
3732 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3733 # @ingroup l2_modif_tofromqu
3734 def ConvertFromQuadratic(self, theSubMesh=None):
3736 self.editor.ConvertFromQuadraticObject(theSubMesh)
3738 return self.editor.ConvertFromQuadratic()
3740 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3741 # @return TRUE if operation has been completed successfully, FALSE otherwise
3742 # @ingroup l2_modif_add
3743 def Make2DMeshFrom3D(self):
3744 return self.editor.Make2DMeshFrom3D()
3746 ## Create missing boundary elements
3747 # @param elements - elements whose boundary is to be checked:
3748 # mesh, group, sub-mesh or list of elements
3749 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3750 # @param dimension - defines type of boundary elements to create, either of
3751 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3752 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3753 # @param groupName - a name of group to store created boundary elements in,
3754 # "" means not to create the group
3755 # @param meshName - a name of new mesh to store created boundary elements in,
3756 # "" means not to create the new mesh
3757 # @param toCopyElements - if true, the checked elements will be copied into
3758 # the new mesh else only boundary elements will be copied into the new mesh
3759 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3760 # boundary elements will be copied into the new mesh
3761 # @return tuple (mesh, group) where boundary elements were added to
3762 # @ingroup l2_modif_add
3763 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3764 toCopyElements=False, toCopyExistingBondary=False):
3765 unRegister = genObjUnRegister()
3766 if isinstance( elements, Mesh ):
3767 elements = elements.GetMesh()
3768 if ( isinstance( elements, list )):
3769 elemType = SMESH.ALL
3770 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3771 elements = self.editor.MakeIDSource(elements, elemType)
3772 unRegister.set( elements )
3773 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3774 toCopyElements,toCopyExistingBondary)
3775 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3779 # @brief Create missing boundary elements around either the whole mesh or
3780 # groups of elements
3781 # @param dimension - defines type of boundary elements to create, either of
3782 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3783 # @param groupName - a name of group to store all boundary elements in,
3784 # "" means not to create the group
3785 # @param meshName - a name of a new mesh, which is a copy of the initial
3786 # mesh + created boundary elements; "" means not to create the new mesh
3787 # @param toCopyAll - if true, the whole initial mesh will be copied into
3788 # the new mesh else only boundary elements will be copied into the new mesh
3789 # @param groups - groups of elements to make boundary around
3790 # @retval tuple( long, mesh, groups )
3791 # long - number of added boundary elements
3792 # mesh - the mesh where elements were added to
3793 # group - the group of boundary elements or None
3795 # @ingroup l2_modif_add
3796 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3797 toCopyAll=False, groups=[]):
3798 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3800 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3801 return nb, mesh, group
3803 ## Renumber mesh nodes (Obsolete, does nothing)
3804 # @ingroup l2_modif_renumber
3805 def RenumberNodes(self):
3806 self.editor.RenumberNodes()
3808 ## Renumber mesh elements (Obsole, does nothing)
3809 # @ingroup l2_modif_renumber
3810 def RenumberElements(self):
3811 self.editor.RenumberElements()
3813 ## Private method converting \a arg into a list of SMESH_IdSource's
3814 def _getIdSourceList(self, arg, idType, unRegister):
3815 if arg and isinstance( arg, list ):
3816 if isinstance( arg[0], int ):
3817 arg = self.GetIDSource( arg, idType )
3818 unRegister.set( arg )
3819 elif isinstance( arg[0], Mesh ):
3820 arg[0] = arg[0].GetMesh()
3821 elif isinstance( arg, Mesh ):
3823 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3827 ## Generate new elements by rotation of the given elements and nodes around the axis
3828 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3829 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3830 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3831 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3832 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3833 # which defines angle in degrees
3834 # @param NbOfSteps the number of steps
3835 # @param Tolerance tolerance
3836 # @param MakeGroups forces the generation of new groups from existing ones
3837 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3838 # of all steps, else - size of each step
3839 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3840 # @ingroup l2_modif_extrurev
3841 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3842 MakeGroups=False, TotalAngle=False):
3843 unRegister = genObjUnRegister()
3844 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3845 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3846 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3848 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3849 Axis = self.smeshpyD.GetAxisStruct( Axis )
3850 if isinstance( Axis, list ):
3851 Axis = SMESH.AxisStruct( *Axis )
3853 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3854 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3855 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3856 self.mesh.SetParameters(Parameters)
3857 if TotalAngle and NbOfSteps:
3858 AngleInRadians /= NbOfSteps
3859 return self.editor.RotationSweepObjects( nodes, edges, faces,
3860 Axis, AngleInRadians,
3861 NbOfSteps, Tolerance, MakeGroups)
3863 ## Generate new elements by rotation of the elements around the axis
3864 # @param IDsOfElements the list of ids of elements to sweep
3865 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3866 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3867 # @param NbOfSteps the number of steps
3868 # @param Tolerance tolerance
3869 # @param MakeGroups forces the generation of new groups from existing ones
3870 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3871 # of all steps, else - size of each step
3872 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3873 # @ingroup l2_modif_extrurev
3874 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3875 MakeGroups=False, TotalAngle=False):
3876 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3877 AngleInRadians, NbOfSteps, Tolerance,
3878 MakeGroups, TotalAngle)
3880 ## Generate new elements by rotation of the elements of object around the axis
3881 # @param theObject object which elements should be sweeped.
3882 # It can be a mesh, a sub mesh or a group.
3883 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3884 # @param AngleInRadians the angle of Rotation
3885 # @param NbOfSteps number of steps
3886 # @param Tolerance tolerance
3887 # @param MakeGroups forces the generation of new groups from existing ones
3888 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3889 # of all steps, else - size of each step
3890 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3891 # @ingroup l2_modif_extrurev
3892 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3893 MakeGroups=False, TotalAngle=False):
3894 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3895 AngleInRadians, NbOfSteps, Tolerance,
3896 MakeGroups, TotalAngle )
3898 ## Generate new elements by rotation of the elements of object around the axis
3899 # @param theObject object which elements should be sweeped.
3900 # It can be a mesh, a sub mesh or a group.
3901 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3902 # @param AngleInRadians the angle of Rotation
3903 # @param NbOfSteps number of steps
3904 # @param Tolerance tolerance
3905 # @param MakeGroups forces the generation of new groups from existing ones
3906 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3907 # of all steps, else - size of each step
3908 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3909 # @ingroup l2_modif_extrurev
3910 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3911 MakeGroups=False, TotalAngle=False):
3912 return self.RotationSweepObjects([],theObject,[], Axis,
3913 AngleInRadians, NbOfSteps, Tolerance,
3914 MakeGroups, TotalAngle)
3916 ## Generate new elements by rotation of the elements of object around the axis
3917 # @param theObject object which elements should be sweeped.
3918 # It can be a mesh, a sub mesh or a group.
3919 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3920 # @param AngleInRadians the angle of Rotation
3921 # @param NbOfSteps number of steps
3922 # @param Tolerance tolerance
3923 # @param MakeGroups forces the generation of new groups from existing ones
3924 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3925 # of all steps, else - size of each step
3926 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3927 # @ingroup l2_modif_extrurev
3928 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3929 MakeGroups=False, TotalAngle=False):
3930 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3931 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3933 ## Generate new elements by extrusion of the given elements and nodes
3934 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3935 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3936 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3937 # @param StepVector vector or DirStruct or 3 vector components, defining
3938 # the direction and value of extrusion for one step (the total extrusion
3939 # length will be NbOfSteps * ||StepVector||)
3940 # @param NbOfSteps the number of steps
3941 # @param MakeGroups forces the generation of new groups from existing ones
3942 # @param scaleFactors optional scale factors to apply during extrusion
3943 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3944 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3945 # @param basePoint optional scaling center; if not provided, a gravity center of
3946 # nodes and elements being extruded is used as the scaling center.
3948 # - a list of tree components of the point or
3951 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3952 # @ingroup l2_modif_extrurev
3953 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3954 scaleFactors=[], linearVariation=False, basePoint=[] ):
3955 unRegister = genObjUnRegister()
3956 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3957 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3958 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3960 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3961 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3962 if isinstance( StepVector, list ):
3963 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3965 if isinstance( basePoint, int):
3966 xyz = self.GetNodeXYZ( basePoint )
3968 raise RuntimeError("Invalid node ID: %s" % basePoint)
3970 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
3971 basePoint = self.geompyD.PointCoordinates( basePoint )
3973 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3974 Parameters = StepVector.PS.parameters + var_separator + Parameters
3975 self.mesh.SetParameters(Parameters)
3977 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3978 StepVector, NbOfSteps,
3979 scaleFactors, linearVariation, basePoint,
3983 ## Generate new elements by extrusion of the elements with given ids
3984 # @param IDsOfElements the list of ids of elements or nodes for extrusion
3985 # @param StepVector vector or DirStruct or 3 vector components, defining
3986 # the direction and value of extrusion for one step (the total extrusion
3987 # length will be NbOfSteps * ||StepVector||)
3988 # @param NbOfSteps the number of steps
3989 # @param MakeGroups forces the generation of new groups from existing ones
3990 # @param IsNodes is True if elements with given ids are nodes
3991 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3992 # @ingroup l2_modif_extrurev
3993 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3995 if IsNodes: n = IDsOfElements
3996 else : e,f, = IDsOfElements,IDsOfElements
3997 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3999 ## Generate new elements by extrusion along the normal to a discretized surface or wire
4000 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
4001 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
4002 # @param StepSize length of one extrusion step (the total extrusion
4003 # length will be \a NbOfSteps * \a StepSize ).
4004 # @param NbOfSteps number of extrusion steps.
4005 # @param ByAverageNormal if True each node is translated by \a StepSize
4006 # along the average of the normal vectors to the faces sharing the node;
4007 # else each node is translated along the same average normal till
4008 # intersection with the plane got by translation of the face sharing
4009 # the node along its own normal by \a StepSize.
4010 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
4011 # for every node of \a Elements.
4012 # @param MakeGroups forces generation of new groups from existing ones.
4013 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
4014 # is not yet implemented. This parameter is used if \a Elements contains
4015 # both faces and edges, i.e. \a Elements is a Mesh.
4016 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
4017 # empty list otherwise.
4018 # @ingroup l2_modif_extrurev
4019 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
4020 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
4021 unRegister = genObjUnRegister()
4022 if isinstance( Elements, Mesh ):
4023 Elements = [ Elements.GetMesh() ]
4024 if isinstance( Elements, list ):
4026 raise RuntimeError("Elements empty!")
4027 if isinstance( Elements[0], int ):
4028 Elements = self.GetIDSource( Elements, SMESH.ALL )
4029 unRegister.set( Elements )
4030 if not isinstance( Elements, list ):
4031 Elements = [ Elements ]
4032 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
4033 self.mesh.SetParameters(Parameters)
4034 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
4035 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
4037 ## Generate new elements by extrusion of the elements or nodes which belong to the object
4038 # @param theObject the object whose elements or nodes should be processed.
4039 # It can be a mesh, a sub-mesh or a group.
4040 # @param StepVector vector or DirStruct or 3 vector components, defining
4041 # the direction and value of extrusion for one step (the total extrusion
4042 # length will be NbOfSteps * ||StepVector||)
4043 # @param NbOfSteps the number of steps
4044 # @param MakeGroups forces the generation of new groups from existing ones
4045 # @param IsNodes is True if elements to extrude are nodes
4046 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4047 # @ingroup l2_modif_extrurev
4048 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4050 if IsNodes: n = theObject
4051 else : e,f, = theObject,theObject
4052 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4054 ## Generate new elements by extrusion of edges which belong to the object
4055 # @param theObject object whose 1D elements should be processed.
4056 # It can be a mesh, a sub-mesh or a group.
4057 # @param StepVector vector or DirStruct or 3 vector components, defining
4058 # the direction and value of extrusion for one step (the total extrusion
4059 # length will be NbOfSteps * ||StepVector||)
4060 # @param NbOfSteps the number of steps
4061 # @param MakeGroups to generate new groups from existing ones
4062 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4063 # @ingroup l2_modif_extrurev
4064 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4065 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4067 ## Generate new elements by extrusion of faces which belong to the object
4068 # @param theObject object whose 2D elements should be processed.
4069 # It can be a mesh, a sub-mesh or a group.
4070 # @param StepVector vector or DirStruct or 3 vector components, defining
4071 # the direction and value of extrusion for one step (the total extrusion
4072 # length will be NbOfSteps * ||StepVector||)
4073 # @param NbOfSteps the number of steps
4074 # @param MakeGroups forces the generation of new groups from existing ones
4075 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4076 # @ingroup l2_modif_extrurev
4077 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4078 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4080 ## Generate new elements by extrusion of the elements with given ids
4081 # @param IDsOfElements is ids of elements
4082 # @param StepVector vector or DirStruct or 3 vector components, defining
4083 # the direction and value of extrusion for one step (the total extrusion
4084 # length will be NbOfSteps * ||StepVector||)
4085 # @param NbOfSteps the number of steps
4086 # @param ExtrFlags sets flags for extrusion
4087 # @param SewTolerance uses for comparing locations of nodes if flag
4088 # EXTRUSION_FLAG_SEW is set
4089 # @param MakeGroups forces the generation of new groups from existing ones
4090 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4091 # @ingroup l2_modif_extrurev
4092 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4093 ExtrFlags, SewTolerance, MakeGroups=False):
4094 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4095 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4096 if isinstance( StepVector, list ):
4097 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4098 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4099 ExtrFlags, SewTolerance, MakeGroups)
4101 ## Generate new elements by extrusion of the given elements and nodes along the path.
4102 # The path of extrusion must be a meshed edge.
4103 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4104 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4105 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4106 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4107 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4108 # contains not only path segments, else it can be None
4109 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4110 # @param HasAngles allows the shape to be rotated around the path
4111 # to get the resulting mesh in a helical fashion
4112 # @param Angles list of angles
4113 # @param LinearVariation forces the computation of rotation angles as linear
4114 # variation of the given Angles along path steps
4115 # @param HasRefPoint allows using the reference point
4116 # @param RefPoint the point around which the shape is rotated (the mass center of the
4117 # shape by default). The User can specify any point as the Reference Point.
4118 # @param MakeGroups forces the generation of new groups from existing ones
4119 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4120 # @ingroup l2_modif_extrurev
4121 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4122 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4123 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4124 unRegister = genObjUnRegister()
4125 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4126 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4127 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4129 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4130 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4131 if isinstance( RefPoint, list ):
4132 if not RefPoint: RefPoint = [0,0,0]
4133 RefPoint = SMESH.PointStruct( *RefPoint )
4134 if isinstance( PathMesh, Mesh ):
4135 PathMesh = PathMesh.GetMesh()
4136 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4137 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4138 self.mesh.SetParameters(Parameters)
4139 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4140 PathMesh, PathShape, NodeStart,
4141 HasAngles, Angles, LinearVariation,
4142 HasRefPoint, RefPoint, MakeGroups)
4144 ## Generate new elements by extrusion of the given elements
4145 # The path of extrusion must be a meshed edge.
4146 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4147 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4148 # @param NodeStart the start node from Path. Defines the direction of extrusion
4149 # @param HasAngles allows the shape to be rotated around the path
4150 # to get the resulting mesh in a helical fashion
4151 # @param Angles list of angles in radians
4152 # @param LinearVariation forces the computation of rotation angles as linear
4153 # variation of the given Angles along path steps
4154 # @param HasRefPoint allows using the reference point
4155 # @param RefPoint the point around which the elements are rotated (the mass
4156 # center of the elements by default).
4157 # The User can specify any point as the Reference Point.
4158 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4159 # @param MakeGroups forces the generation of new groups from existing ones
4160 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4161 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4162 # only SMESH::Extrusion_Error otherwise
4163 # @ingroup l2_modif_extrurev
4164 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4165 HasAngles=False, Angles=[], LinearVariation=False,
4166 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4167 ElemType=SMESH.FACE):
4169 if ElemType == SMESH.NODE: n = Base
4170 if ElemType == SMESH.EDGE: e = Base
4171 if ElemType == SMESH.FACE: f = Base
4172 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4173 HasAngles, Angles, LinearVariation,
4174 HasRefPoint, RefPoint, MakeGroups)
4175 if MakeGroups: return gr,er
4178 ## Generate new elements by extrusion of the given elements
4179 # The path of extrusion must be a meshed edge.
4180 # @param IDsOfElements ids of elements
4181 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4182 # @param PathShape shape(edge) defines the sub-mesh for the path
4183 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4184 # @param HasAngles allows the shape to be rotated around the path
4185 # to get the resulting mesh in a helical fashion
4186 # @param Angles list of angles in radians
4187 # @param HasRefPoint allows using the reference point
4188 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4189 # The User can specify any point as the Reference Point.
4190 # @param MakeGroups forces the generation of new groups from existing ones
4191 # @param LinearVariation forces the computation of rotation angles as linear
4192 # variation of the given Angles along path steps
4193 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4194 # only SMESH::Extrusion_Error otherwise
4195 # @ingroup l2_modif_extrurev
4196 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4197 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4198 MakeGroups=False, LinearVariation=False):
4199 n,e,f = [],IDsOfElements,IDsOfElements
4200 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4201 NodeStart, HasAngles, Angles,
4203 HasRefPoint, RefPoint, MakeGroups)
4204 if MakeGroups: return gr,er
4207 ## Generate new elements by extrusion of the elements which belong to the object
4208 # The path of extrusion must be a meshed edge.
4209 # @param theObject the object whose elements should be processed.
4210 # It can be a mesh, a sub-mesh or a group.
4211 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4212 # @param PathShape shape(edge) defines the sub-mesh for the path
4213 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4214 # @param HasAngles allows the shape to be rotated around the path
4215 # to get the resulting mesh in a helical fashion
4216 # @param Angles list of angles
4217 # @param HasRefPoint allows using the reference point
4218 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4219 # The User can specify any point as the Reference Point.
4220 # @param MakeGroups forces the generation of new groups from existing ones
4221 # @param LinearVariation forces the computation of rotation angles as linear
4222 # variation of the given Angles along path steps
4223 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4224 # only SMESH::Extrusion_Error otherwise
4225 # @ingroup l2_modif_extrurev
4226 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4227 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4228 MakeGroups=False, LinearVariation=False):
4229 n,e,f = [],theObject,theObject
4230 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4231 HasAngles, Angles, LinearVariation,
4232 HasRefPoint, RefPoint, MakeGroups)
4233 if MakeGroups: return gr,er
4236 ## Generate new elements by extrusion of mesh segments which belong to the object
4237 # The path of extrusion must be a meshed edge.
4238 # @param theObject the object whose 1D elements should be processed.
4239 # It can be a mesh, a sub-mesh or a group.
4240 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4241 # @param PathShape shape(edge) defines the sub-mesh for the path
4242 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4243 # @param HasAngles allows the shape to be rotated around the path
4244 # to get the resulting mesh in a helical fashion
4245 # @param Angles list of angles
4246 # @param HasRefPoint allows using the reference point
4247 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4248 # The User can specify any point as the Reference Point.
4249 # @param MakeGroups forces the generation of new groups from existing ones
4250 # @param LinearVariation forces the computation of rotation angles as linear
4251 # variation of the given Angles along path steps
4252 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4253 # only SMESH::Extrusion_Error otherwise
4254 # @ingroup l2_modif_extrurev
4255 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4256 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4257 MakeGroups=False, LinearVariation=False):
4258 n,e,f = [],theObject,[]
4259 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4260 HasAngles, Angles, LinearVariation,
4261 HasRefPoint, RefPoint, MakeGroups)
4262 if MakeGroups: return gr,er
4265 ## Generate new elements by extrusion of faces which belong to the object
4266 # The path of extrusion must be a meshed edge.
4267 # @param theObject the object whose 2D elements should be processed.
4268 # It can be a mesh, a sub-mesh or a group.
4269 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4270 # @param PathShape shape(edge) defines the sub-mesh for the path
4271 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4272 # @param HasAngles allows the shape to be rotated around the path
4273 # to get the resulting mesh in a helical fashion
4274 # @param Angles list of angles
4275 # @param HasRefPoint allows using the reference point
4276 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4277 # The User can specify any point as the Reference Point.
4278 # @param MakeGroups forces the generation of new groups from existing ones
4279 # @param LinearVariation forces the computation of rotation angles as linear
4280 # variation of the given Angles along path steps
4281 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4282 # only SMESH::Extrusion_Error otherwise
4283 # @ingroup l2_modif_extrurev
4284 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4285 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4286 MakeGroups=False, LinearVariation=False):
4287 n,e,f = [],[],theObject
4288 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4289 HasAngles, Angles, LinearVariation,
4290 HasRefPoint, RefPoint, MakeGroups)
4291 if MakeGroups: return gr,er
4294 ## Create a symmetrical copy of mesh elements
4295 # @param IDsOfElements list of elements ids
4296 # @param Mirror is AxisStruct or geom object(point, line, plane)
4297 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4298 # If the Mirror is a geom object this parameter is unnecessary
4299 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4300 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4301 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4302 # @ingroup l2_modif_trsf
4303 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4304 if IDsOfElements == []:
4305 IDsOfElements = self.GetElementsId()
4306 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4307 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4308 theMirrorType = Mirror._mirrorType
4310 self.mesh.SetParameters(Mirror.parameters)
4311 if Copy and MakeGroups:
4312 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4313 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4316 ## Create a new mesh by a symmetrical copy of mesh elements
4317 # @param IDsOfElements the list of elements ids
4318 # @param Mirror is AxisStruct or geom object (point, line, plane)
4319 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4320 # If the Mirror is a geom object this parameter is unnecessary
4321 # @param MakeGroups to generate new groups from existing ones
4322 # @param NewMeshName a name of the new mesh to create
4323 # @return instance of Mesh class
4324 # @ingroup l2_modif_trsf
4325 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4326 if IDsOfElements == []:
4327 IDsOfElements = self.GetElementsId()
4328 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4329 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4330 theMirrorType = Mirror._mirrorType
4332 self.mesh.SetParameters(Mirror.parameters)
4333 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4334 MakeGroups, NewMeshName)
4335 return Mesh(self.smeshpyD,self.geompyD,mesh)
4337 ## Create a symmetrical copy of the object
4338 # @param theObject mesh, submesh or group
4339 # @param Mirror AxisStruct or geom object (point, line, plane)
4340 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4341 # If the Mirror is a geom object this parameter is unnecessary
4342 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4343 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4344 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4345 # @ingroup l2_modif_trsf
4346 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4347 if ( isinstance( theObject, Mesh )):
4348 theObject = theObject.GetMesh()
4349 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4350 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4351 theMirrorType = Mirror._mirrorType
4353 self.mesh.SetParameters(Mirror.parameters)
4354 if Copy and MakeGroups:
4355 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4356 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4359 ## Create a new mesh by a symmetrical copy of the object
4360 # @param theObject mesh, submesh or group
4361 # @param Mirror AxisStruct or geom object (point, line, plane)
4362 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4363 # If the Mirror is a geom object this parameter is unnecessary
4364 # @param MakeGroups forces the generation of new groups from existing ones
4365 # @param NewMeshName the name of the new mesh to create
4366 # @return instance of Mesh class
4367 # @ingroup l2_modif_trsf
4368 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4369 if ( isinstance( theObject, Mesh )):
4370 theObject = theObject.GetMesh()
4371 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4372 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4373 theMirrorType = Mirror._mirrorType
4375 self.mesh.SetParameters(Mirror.parameters)
4376 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4377 MakeGroups, NewMeshName)
4378 return Mesh( self.smeshpyD,self.geompyD,mesh )
4380 ## Translate the elements
4381 # @param IDsOfElements list of elements ids
4382 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4383 # @param Copy allows copying the translated elements
4384 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4385 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4386 # @ingroup l2_modif_trsf
4387 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4388 if IDsOfElements == []:
4389 IDsOfElements = self.GetElementsId()
4390 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4391 Vector = self.smeshpyD.GetDirStruct(Vector)
4392 if isinstance( Vector, list ):
4393 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4394 self.mesh.SetParameters(Vector.PS.parameters)
4395 if Copy and MakeGroups:
4396 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4397 self.editor.Translate(IDsOfElements, Vector, Copy)
4400 ## Create a new mesh of translated elements
4401 # @param IDsOfElements list of elements ids
4402 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4403 # @param MakeGroups forces the generation of new groups from existing ones
4404 # @param NewMeshName the name of the newly created mesh
4405 # @return instance of Mesh class
4406 # @ingroup l2_modif_trsf
4407 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4408 if IDsOfElements == []:
4409 IDsOfElements = self.GetElementsId()
4410 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4411 Vector = self.smeshpyD.GetDirStruct(Vector)
4412 if isinstance( Vector, list ):
4413 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4414 self.mesh.SetParameters(Vector.PS.parameters)
4415 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4416 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4418 ## Translate the object
4419 # @param theObject the object to translate (mesh, submesh, or group)
4420 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4421 # @param Copy allows copying the translated elements
4422 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4423 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4424 # @ingroup l2_modif_trsf
4425 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4426 if ( isinstance( theObject, Mesh )):
4427 theObject = theObject.GetMesh()
4428 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4429 Vector = self.smeshpyD.GetDirStruct(Vector)
4430 if isinstance( Vector, list ):
4431 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4432 self.mesh.SetParameters(Vector.PS.parameters)
4433 if Copy and MakeGroups:
4434 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4435 self.editor.TranslateObject(theObject, Vector, Copy)
4438 ## Create a new mesh from the translated object
4439 # @param theObject the object to translate (mesh, submesh, or group)
4440 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4441 # @param MakeGroups forces the generation of new groups from existing ones
4442 # @param NewMeshName the name of the newly created mesh
4443 # @return instance of Mesh class
4444 # @ingroup l2_modif_trsf
4445 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4446 if isinstance( theObject, Mesh ):
4447 theObject = theObject.GetMesh()
4448 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4449 Vector = self.smeshpyD.GetDirStruct(Vector)
4450 if isinstance( Vector, list ):
4451 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4452 self.mesh.SetParameters(Vector.PS.parameters)
4453 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4454 return Mesh( self.smeshpyD, self.geompyD, mesh )
4459 # @param theObject - the object to translate (mesh, submesh, or group)
4460 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4461 # @param theScaleFact - list of 1-3 scale factors for axises
4462 # @param Copy - allows copying the translated elements
4463 # @param MakeGroups - forces the generation of new groups from existing
4465 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4466 # empty list otherwise
4467 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4468 unRegister = genObjUnRegister()
4469 if ( isinstance( theObject, Mesh )):
4470 theObject = theObject.GetMesh()
4471 if ( isinstance( theObject, list )):
4472 theObject = self.GetIDSource(theObject, SMESH.ALL)
4473 unRegister.set( theObject )
4474 if ( isinstance( thePoint, list )):
4475 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4476 if ( isinstance( theScaleFact, float )):
4477 theScaleFact = [theScaleFact]
4478 if ( isinstance( theScaleFact, int )):
4479 theScaleFact = [ float(theScaleFact)]
4481 self.mesh.SetParameters(thePoint.parameters)
4483 if Copy and MakeGroups:
4484 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4485 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4488 ## Create a new mesh from the translated object
4489 # @param theObject - the object to translate (mesh, submesh, or group)
4490 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4491 # @param theScaleFact - list of 1-3 scale factors for axises
4492 # @param MakeGroups - forces the generation of new groups from existing ones
4493 # @param NewMeshName - the name of the newly created mesh
4494 # @return instance of Mesh class
4495 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4496 unRegister = genObjUnRegister()
4497 if (isinstance(theObject, Mesh)):
4498 theObject = theObject.GetMesh()
4499 if ( isinstance( theObject, list )):
4500 theObject = self.GetIDSource(theObject,SMESH.ALL)
4501 unRegister.set( theObject )
4502 if ( isinstance( thePoint, list )):
4503 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4504 if ( isinstance( theScaleFact, float )):
4505 theScaleFact = [theScaleFact]
4506 if ( isinstance( theScaleFact, int )):
4507 theScaleFact = [ float(theScaleFact)]
4509 self.mesh.SetParameters(thePoint.parameters)
4510 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4511 MakeGroups, NewMeshName)
4512 return Mesh( self.smeshpyD, self.geompyD, mesh )
4516 ## Rotate the elements
4517 # @param IDsOfElements list of elements ids
4518 # @param Axis the axis of rotation (AxisStruct or geom line)
4519 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4520 # @param Copy allows copying the rotated elements
4521 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4522 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4523 # @ingroup l2_modif_trsf
4524 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4525 if IDsOfElements == []:
4526 IDsOfElements = self.GetElementsId()
4527 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4528 Axis = self.smeshpyD.GetAxisStruct(Axis)
4529 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4530 Parameters = Axis.parameters + var_separator + Parameters
4531 self.mesh.SetParameters(Parameters)
4532 if Copy and MakeGroups:
4533 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4534 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4537 ## Create a new mesh of rotated elements
4538 # @param IDsOfElements list of element ids
4539 # @param Axis the axis of rotation (AxisStruct or geom line)
4540 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4541 # @param MakeGroups forces the generation of new groups from existing ones
4542 # @param NewMeshName the name of the newly created mesh
4543 # @return instance of Mesh class
4544 # @ingroup l2_modif_trsf
4545 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4546 if IDsOfElements == []:
4547 IDsOfElements = self.GetElementsId()
4548 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4549 Axis = self.smeshpyD.GetAxisStruct(Axis)
4550 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4551 Parameters = Axis.parameters + var_separator + Parameters
4552 self.mesh.SetParameters(Parameters)
4553 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4554 MakeGroups, NewMeshName)
4555 return Mesh( self.smeshpyD, self.geompyD, mesh )
4557 ## Rotate the object
4558 # @param theObject the object to rotate( mesh, submesh, or group)
4559 # @param Axis the axis of rotation (AxisStruct or geom line)
4560 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4561 # @param Copy allows copying the rotated elements
4562 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4563 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4564 # @ingroup l2_modif_trsf
4565 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4566 if (isinstance(theObject, Mesh)):
4567 theObject = theObject.GetMesh()
4568 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4569 Axis = self.smeshpyD.GetAxisStruct(Axis)
4570 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4571 Parameters = Axis.parameters + ":" + Parameters
4572 self.mesh.SetParameters(Parameters)
4573 if Copy and MakeGroups:
4574 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4575 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4578 ## Create a new mesh from the rotated object
4579 # @param theObject the object to rotate (mesh, submesh, or group)
4580 # @param Axis the axis of rotation (AxisStruct or geom line)
4581 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4582 # @param MakeGroups forces the generation of new groups from existing ones
4583 # @param NewMeshName the name of the newly created mesh
4584 # @return instance of Mesh class
4585 # @ingroup l2_modif_trsf
4586 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4587 if (isinstance( theObject, Mesh )):
4588 theObject = theObject.GetMesh()
4589 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4590 Axis = self.smeshpyD.GetAxisStruct(Axis)
4591 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4592 Parameters = Axis.parameters + ":" + Parameters
4593 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4594 MakeGroups, NewMeshName)
4595 self.mesh.SetParameters(Parameters)
4596 return Mesh( self.smeshpyD, self.geompyD, mesh )
4598 ## Find groups of adjacent nodes within Tolerance.
4599 # @param Tolerance the value of tolerance
4600 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4601 # corner and medium nodes in separate groups thus preventing
4602 # their further merge.
4603 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4604 # @ingroup l2_modif_trsf
4605 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4606 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4608 ## Find groups of ajacent nodes within Tolerance.
4609 # @param Tolerance the value of tolerance
4610 # @param SubMeshOrGroup SubMesh, Group or Filter
4611 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4612 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4613 # corner and medium nodes in separate groups thus preventing
4614 # their further merge.
4615 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4616 # @ingroup l2_modif_trsf
4617 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4618 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4619 unRegister = genObjUnRegister()
4620 if (isinstance( SubMeshOrGroup, Mesh )):
4621 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4622 if not isinstance( exceptNodes, list ):
4623 exceptNodes = [ exceptNodes ]
4624 if exceptNodes and isinstance( exceptNodes[0], int ):
4625 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4626 unRegister.set( exceptNodes )
4627 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4628 exceptNodes, SeparateCornerAndMediumNodes)
4631 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4632 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4633 # by nodes 1 and 25 correspondingly in all elements and groups
4634 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4635 # If @a NodesToKeep does not include a node to keep for some group to merge,
4636 # then the first node in the group is kept.
4637 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4639 # @ingroup l2_modif_trsf
4640 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4641 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4642 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4644 ## Find the elements built on the same nodes.
4645 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4646 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4647 # @ingroup l2_modif_trsf
4648 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4649 if not MeshOrSubMeshOrGroup:
4650 MeshOrSubMeshOrGroup=self.mesh
4651 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4652 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4653 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4655 ## Merge elements in each given group.
4656 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4657 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4658 # replaced by elements 1 and 25 in all groups)
4659 # @ingroup l2_modif_trsf
4660 def MergeElements(self, GroupsOfElementsID):
4661 self.editor.MergeElements(GroupsOfElementsID)
4663 ## Leave one element and remove all other elements built on the same nodes.
4664 # @ingroup l2_modif_trsf
4665 def MergeEqualElements(self):
4666 self.editor.MergeEqualElements()
4668 ## Return groups of FreeBorder's coincident within the given tolerance.
4669 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4670 # size of elements adjacent to free borders being compared is used.
4671 # @return SMESH.CoincidentFreeBorders structure
4672 # @ingroup l2_modif_trsf
4673 def FindCoincidentFreeBorders (self, tolerance=0.):
4674 return self.editor.FindCoincidentFreeBorders( tolerance )
4676 ## Sew FreeBorder's of each group
4677 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4678 # where each enclosed list contains node IDs of a group of coincident free
4679 # borders such that each consequent triple of IDs within a group describes
4680 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4681 # last node of a border.
4682 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4683 # groups of coincident free borders, each group including two borders.
4684 # @param createPolygons if @c True faces adjacent to free borders are converted to
4685 # polygons if a node of opposite border falls on a face edge, else such
4686 # faces are split into several ones.
4687 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4688 # polyhedra if a node of opposite border falls on a volume edge, else such
4689 # volumes, if any, remain intact and the mesh becomes non-conformal.
4690 # @return a number of successfully sewed groups
4691 # @ingroup l2_modif_trsf
4692 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4693 if freeBorders and isinstance( freeBorders, list ):
4694 # construct SMESH.CoincidentFreeBorders
4695 if isinstance( freeBorders[0], int ):
4696 freeBorders = [freeBorders]
4698 coincidentGroups = []
4699 for nodeList in freeBorders:
4700 if not nodeList or len( nodeList ) % 3:
4701 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
4704 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4705 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4706 nodeList = nodeList[3:]
4708 coincidentGroups.append( group )
4710 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4712 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4715 # @return SMESH::Sew_Error
4716 # @ingroup l2_modif_trsf
4717 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4718 FirstNodeID2, SecondNodeID2, LastNodeID2,
4719 CreatePolygons, CreatePolyedrs):
4720 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4721 FirstNodeID2, SecondNodeID2, LastNodeID2,
4722 CreatePolygons, CreatePolyedrs)
4724 ## Sew conform free borders
4725 # @return SMESH::Sew_Error
4726 # @ingroup l2_modif_trsf
4727 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4728 FirstNodeID2, SecondNodeID2):
4729 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4730 FirstNodeID2, SecondNodeID2)
4732 ## Sew border to side
4733 # @return SMESH::Sew_Error
4734 # @ingroup l2_modif_trsf
4735 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4736 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4737 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4738 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4740 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4741 # merged with the nodes of elements of Side2.
4742 # The number of elements in theSide1 and in theSide2 must be
4743 # equal and they should have similar nodal connectivity.
4744 # The nodes to merge should belong to side borders and
4745 # the first node should be linked to the second.
4746 # @return SMESH::Sew_Error
4747 # @ingroup l2_modif_trsf
4748 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4749 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4750 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4751 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4752 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4753 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4755 ## Set new nodes for the given element.
4756 # @param ide the element id
4757 # @param newIDs nodes ids
4758 # @return If the number of nodes does not correspond to the type of element - return false
4759 # @ingroup l2_modif_edit
4760 def ChangeElemNodes(self, ide, newIDs):
4761 return self.editor.ChangeElemNodes(ide, newIDs)
4763 ## If during the last operation of MeshEditor some nodes were
4764 # created, this method return the list of their IDs, \n
4765 # if new nodes were not created - return empty list
4766 # @return the list of integer values (can be empty)
4767 # @ingroup l2_modif_add
4768 def GetLastCreatedNodes(self):
4769 return self.editor.GetLastCreatedNodes()
4771 ## If during the last operation of MeshEditor some elements were
4772 # created this method return the list of their IDs, \n
4773 # if new elements were not created - return empty list
4774 # @return the list of integer values (can be empty)
4775 # @ingroup l2_modif_add
4776 def GetLastCreatedElems(self):
4777 return self.editor.GetLastCreatedElems()
4779 ## Forget what nodes and elements were created by the last mesh edition operation
4780 # @ingroup l2_modif_add
4781 def ClearLastCreated(self):
4782 self.editor.ClearLastCreated()
4784 ## Create duplicates of given elements, i.e. create new elements based on the
4785 # same nodes as the given ones.
4786 # @param theElements - container of elements to duplicate. It can be a Mesh,
4787 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4788 # a Mesh, elements of highest dimension are duplicated
4789 # @param theGroupName - a name of group to contain the generated elements.
4790 # If a group with such a name already exists, the new elements
4791 # are added to the existng group, else a new group is created.
4792 # If \a theGroupName is empty, new elements are not added
4794 # @return a group where the new elements are added. None if theGroupName == "".
4795 # @ingroup l2_modif_duplicat
4796 def DoubleElements(self, theElements, theGroupName=""):
4797 unRegister = genObjUnRegister()
4798 if isinstance( theElements, Mesh ):
4799 theElements = theElements.mesh
4800 elif isinstance( theElements, list ):
4801 theElements = self.GetIDSource( theElements, SMESH.ALL )
4802 unRegister.set( theElements )
4803 return self.editor.DoubleElements(theElements, theGroupName)
4805 ## Create a hole in a mesh by doubling the nodes of some particular elements
4806 # @param theNodes identifiers of nodes to be doubled
4807 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4808 # nodes. If list of element identifiers is empty then nodes are doubled but
4809 # they not assigned to elements
4810 # @return TRUE if operation has been completed successfully, FALSE otherwise
4811 # @ingroup l2_modif_duplicat
4812 def DoubleNodes(self, theNodes, theModifiedElems):
4813 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4815 ## Create a hole in a mesh by doubling the nodes of some particular elements
4816 # This method provided for convenience works as DoubleNodes() described above.
4817 # @param theNodeId identifiers of node to be doubled
4818 # @param theModifiedElems identifiers of elements to be updated
4819 # @return TRUE if operation has been completed successfully, FALSE otherwise
4820 # @ingroup l2_modif_duplicat
4821 def DoubleNode(self, theNodeId, theModifiedElems):
4822 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4824 ## Create a hole in a mesh by doubling the nodes of some particular elements
4825 # This method provided for convenience works as DoubleNodes() described above.
4826 # @param theNodes group of nodes to be doubled
4827 # @param theModifiedElems group of elements to be updated.
4828 # @param theMakeGroup forces the generation of a group containing new nodes.
4829 # @return TRUE or a created group if operation has been completed successfully,
4830 # FALSE or None otherwise
4831 # @ingroup l2_modif_duplicat
4832 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4834 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4835 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4837 ## Create a hole in a mesh by doubling the nodes of some particular elements
4838 # This method provided for convenience works as DoubleNodes() described above.
4839 # @param theNodes list of groups of nodes to be doubled
4840 # @param theModifiedElems list of groups of elements to be updated.
4841 # @param theMakeGroup forces the generation of a group containing new nodes.
4842 # @return TRUE if operation has been completed successfully, FALSE otherwise
4843 # @ingroup l2_modif_duplicat
4844 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4846 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4847 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4849 ## Create a hole in a mesh by doubling the nodes of some particular elements
4850 # @param theElems - the list of elements (edges or faces) to be replicated
4851 # The nodes for duplication could be found from these elements
4852 # @param theNodesNot - list of nodes to NOT replicate
4853 # @param theAffectedElems - the list of elements (cells and edges) to which the
4854 # replicated nodes should be associated to.
4855 # @return TRUE if operation has been completed successfully, FALSE otherwise
4856 # @ingroup l2_modif_duplicat
4857 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4858 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4860 ## Create a hole in a mesh by doubling the nodes of some particular elements
4861 # @param theElems - the list of elements (edges or faces) to be replicated
4862 # The nodes for duplication could be found from these elements
4863 # @param theNodesNot - list of nodes to NOT replicate
4864 # @param theShape - shape to detect affected elements (element which geometric center
4865 # located on or inside shape).
4866 # The replicated nodes should be associated to affected elements.
4867 # @return TRUE if operation has been completed successfully, FALSE otherwise
4868 # @ingroup l2_modif_duplicat
4869 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4870 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4872 ## Create a hole in a mesh by doubling the nodes of some particular elements
4873 # This method provided for convenience works as DoubleNodes() described above.
4874 # @param theElems - group of of elements (edges or faces) to be replicated
4875 # @param theNodesNot - group of nodes not to replicated
4876 # @param theAffectedElems - group of elements to which the replicated nodes
4877 # should be associated to.
4878 # @param theMakeGroup forces the generation of a group containing new elements.
4879 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4880 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4881 # FALSE or None otherwise
4882 # @ingroup l2_modif_duplicat
4883 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4884 theMakeGroup=False, theMakeNodeGroup=False):
4885 if theMakeGroup or theMakeNodeGroup:
4886 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4888 theMakeGroup, theMakeNodeGroup)
4889 if theMakeGroup and theMakeNodeGroup:
4892 return twoGroups[ int(theMakeNodeGroup) ]
4893 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4895 ## Create a hole in a mesh by doubling the nodes of some particular elements
4896 # This method provided for convenience works as DoubleNodes() described above.
4897 # @param theElems - group of of elements (edges or faces) to be replicated
4898 # @param theNodesNot - group of nodes not to replicated
4899 # @param theShape - shape to detect affected elements (element which geometric center
4900 # located on or inside shape).
4901 # The replicated nodes should be associated to affected elements.
4902 # @ingroup l2_modif_duplicat
4903 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4904 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4906 ## Create a hole in a mesh by doubling the nodes of some particular elements
4907 # This method provided for convenience works as DoubleNodes() described above.
4908 # @param theElems - list of groups of elements (edges or faces) to be replicated
4909 # @param theNodesNot - list of groups of nodes not to replicated
4910 # @param theAffectedElems - group of elements to which the replicated nodes
4911 # should be associated to.
4912 # @param theMakeGroup forces the generation of a group containing new elements.
4913 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4914 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4915 # FALSE or None otherwise
4916 # @ingroup l2_modif_duplicat
4917 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4918 theMakeGroup=False, theMakeNodeGroup=False):
4919 if theMakeGroup or theMakeNodeGroup:
4920 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4922 theMakeGroup, theMakeNodeGroup)
4923 if theMakeGroup and theMakeNodeGroup:
4926 return twoGroups[ int(theMakeNodeGroup) ]
4927 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4929 ## Create a hole in a mesh by doubling the nodes of some particular elements
4930 # This method provided for convenience works as DoubleNodes() described above.
4931 # @param theElems - list of groups of elements (edges or faces) to be replicated
4932 # @param theNodesNot - list of groups of nodes not to replicated
4933 # @param theShape - shape to detect affected elements (element which geometric center
4934 # located on or inside shape).
4935 # The replicated nodes should be associated to affected elements.
4936 # @return TRUE if operation has been completed successfully, FALSE otherwise
4937 # @ingroup l2_modif_duplicat
4938 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4939 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4941 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4942 # This method is the first step of DoubleNodeElemGroupsInRegion.
4943 # @param theElems - list of groups of elements (edges or faces) to be replicated
4944 # @param theNodesNot - list of groups of nodes not to replicated
4945 # @param theShape - shape to detect affected elements (element which geometric center
4946 # located on or inside shape).
4947 # The replicated nodes should be associated to affected elements.
4948 # @return groups of affected elements
4949 # @ingroup l2_modif_duplicat
4950 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4951 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4953 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4954 # The list of groups must describe a partition of the mesh volumes.
4955 # The nodes of the internal faces at the boundaries of the groups are doubled.
4956 # In option, the internal faces are replaced by flat elements.
4957 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4958 # @param theDomains - list of groups of volumes
4959 # @param createJointElems - if TRUE, create the elements
4960 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4961 # the boundary between \a theDomains and the rest mesh
4962 # @return TRUE if operation has been completed successfully, FALSE otherwise
4963 # @ingroup l2_modif_duplicat
4964 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4965 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4967 ## Double nodes on some external faces and create flat elements.
4968 # Flat elements are mainly used by some types of mechanic calculations.
4970 # Each group of the list must be constituted of faces.
4971 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4972 # @param theGroupsOfFaces - list of groups of faces
4973 # @return TRUE if operation has been completed successfully, FALSE otherwise
4974 # @ingroup l2_modif_duplicat
4975 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4976 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4978 ## identify all the elements around a geom shape, get the faces delimiting the hole
4980 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4981 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4983 def _getFunctor(self, funcType ):
4984 fn = self.functors[ EnumToLong(funcType) ]
4986 fn = self.smeshpyD.GetFunctor(funcType)
4987 fn.SetMesh(self.mesh)
4988 self.functors[ EnumToLong(funcType) ] = fn
4991 ## Return value of a functor for a given element
4992 # @param funcType an item of SMESH.FunctorType enum
4993 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
4994 # @param elemId element or node ID
4995 # @param isElem @a elemId is ID of element or node
4996 # @return the functor value or zero in case of invalid arguments
4997 # @ingroup l1_measurements
4998 def FunctorValue(self, funcType, elemId, isElem=True):
4999 fn = self._getFunctor( funcType )
5000 if fn.GetElementType() == self.GetElementType(elemId, isElem):
5001 val = fn.GetValue(elemId)
5006 ## Get length of 1D element or sum of lengths of all 1D mesh elements
5007 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
5008 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
5009 # @ingroup l1_measurements
5010 def GetLength(self, elemId=None):
5013 length = self.smeshpyD.GetLength(self)
5015 length = self.FunctorValue(SMESH.FT_Length, elemId)
5018 ## Get area of 2D element or sum of areas of all 2D mesh elements
5019 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5020 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5021 # @ingroup l1_measurements
5022 def GetArea(self, elemId=None):
5025 area = self.smeshpyD.GetArea(self)
5027 area = self.FunctorValue(SMESH.FT_Area, elemId)
5030 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5031 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5032 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5033 # @ingroup l1_measurements
5034 def GetVolume(self, elemId=None):
5037 volume = self.smeshpyD.GetVolume(self)
5039 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5042 ## Get maximum element length.
5043 # @param elemId mesh element ID
5044 # @return element's maximum length value
5045 # @ingroup l1_measurements
5046 def GetMaxElementLength(self, elemId):
5047 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5048 ftype = SMESH.FT_MaxElementLength3D
5050 ftype = SMESH.FT_MaxElementLength2D
5051 return self.FunctorValue(ftype, elemId)
5053 ## Get aspect ratio of 2D or 3D element.
5054 # @param elemId mesh element ID
5055 # @return element's aspect ratio value
5056 # @ingroup l1_measurements
5057 def GetAspectRatio(self, elemId):
5058 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5059 ftype = SMESH.FT_AspectRatio3D
5061 ftype = SMESH.FT_AspectRatio
5062 return self.FunctorValue(ftype, elemId)
5064 ## Get warping angle of 2D element.
5065 # @param elemId mesh element ID
5066 # @return element's warping angle value
5067 # @ingroup l1_measurements
5068 def GetWarping(self, elemId):
5069 return self.FunctorValue(SMESH.FT_Warping, elemId)
5071 ## Get minimum angle of 2D element.
5072 # @param elemId mesh element ID
5073 # @return element's minimum angle value
5074 # @ingroup l1_measurements
5075 def GetMinimumAngle(self, elemId):
5076 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5078 ## Get taper of 2D element.
5079 # @param elemId mesh element ID
5080 # @return element's taper value
5081 # @ingroup l1_measurements
5082 def GetTaper(self, elemId):
5083 return self.FunctorValue(SMESH.FT_Taper, elemId)
5085 ## Get skew of 2D element.
5086 # @param elemId mesh element ID
5087 # @return element's skew value
5088 # @ingroup l1_measurements
5089 def GetSkew(self, elemId):
5090 return self.FunctorValue(SMESH.FT_Skew, elemId)
5092 ## Return minimal and maximal value of a given functor.
5093 # @param funType a functor type, an item of SMESH.FunctorType enum
5094 # (one of SMESH.FunctorType._items)
5095 # @param meshPart a part of mesh (group, sub-mesh) to treat
5096 # @return tuple (min,max)
5097 # @ingroup l1_measurements
5098 def GetMinMax(self, funType, meshPart=None):
5099 unRegister = genObjUnRegister()
5100 if isinstance( meshPart, list ):
5101 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5102 unRegister.set( meshPart )
5103 if isinstance( meshPart, Mesh ):
5104 meshPart = meshPart.mesh
5105 fun = self._getFunctor( funType )
5108 if hasattr( meshPart, "SetMesh" ):
5109 meshPart.SetMesh( self.mesh ) # set mesh to filter
5110 hist = fun.GetLocalHistogram( 1, False, meshPart )
5112 hist = fun.GetHistogram( 1, False )
5114 return hist[0].min, hist[0].max
5117 pass # end of Mesh class
5120 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5121 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5123 class meshProxy(SMESH._objref_SMESH_Mesh):
5124 def __init__(self, *args):
5125 SMESH._objref_SMESH_Mesh.__init__(self, *args)
5126 def __deepcopy__(self, memo=None):
5127 new = self.__class__(self)
5129 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5130 if len( args ) == 3:
5131 args += SMESH.ALL_NODES, True
5132 return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
5134 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5137 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5139 class submeshProxy(SMESH._objref_SMESH_subMesh):
5140 def __init__(self, *args):
5141 SMESH._objref_SMESH_subMesh.__init__(self, *args)
5143 def __deepcopy__(self, memo=None):
5144 new = self.__class__(self)
5147 ## Compute the sub-mesh and return the status of the computation
5148 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5149 # @return True or False
5151 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5152 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5153 # @ingroup l2_submeshes
5154 def Compute(self,refresh=False):
5156 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5158 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5160 if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
5161 smeshgui = salome.ImportComponentGUI("SMESH")
5162 smeshgui.Init(self.mesh.GetStudyId())
5163 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5164 if refresh: salome.sg.updateObjBrowser(True)
5169 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5172 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5173 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5176 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5177 def __init__(self, *args):
5178 SMESH._objref_SMESH_MeshEditor.__init__(self, *args)
5180 def __getattr__(self, name ): # method called if an attribute not found
5181 if not self.mesh: # look for name() method in Mesh class
5182 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5183 if hasattr( self.mesh, name ):
5184 return getattr( self.mesh, name )
5185 if name == "ExtrusionAlongPathObjX":
5186 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5187 print("meshEditor: attribute '%s' NOT FOUND" % name)
5189 def __deepcopy__(self, memo=None):
5190 new = self.__class__(self)
5192 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5193 if len( args ) == 1: args += False,
5194 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5195 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5196 if len( args ) == 2: args += False,
5197 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5198 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5199 if len( args ) == 1:
5200 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5201 NodesToKeep = args[1]
5202 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5203 unRegister = genObjUnRegister()
5205 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5206 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5207 if not isinstance( NodesToKeep, list ):
5208 NodesToKeep = [ NodesToKeep ]
5209 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5211 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5213 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5214 # variables in some methods
5216 class Pattern(SMESH._objref_SMESH_Pattern):
5218 def LoadFromFile(self, patternTextOrFile ):
5219 text = patternTextOrFile
5220 if os.path.exists( text ):
5221 text = open( patternTextOrFile ).read()
5223 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5225 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5226 decrFun = lambda i: i-1
5227 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5228 theMesh.SetParameters(Parameters)
5229 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5231 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5232 decrFun = lambda i: i-1
5233 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5234 theMesh.SetParameters(Parameters)
5235 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5237 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5238 if isinstance( mesh, Mesh ):
5239 mesh = mesh.GetMesh()
5240 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5242 # Registering the new proxy for Pattern
5243 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5245 ## Private class used to bind methods creating algorithms to the class Mesh
5250 self.defaultAlgoType = ""
5251 self.algoTypeToClass = {}
5253 # Store a python class of algorithm
5254 def add(self, algoClass):
5255 if inspect.isclass(algoClass) and \
5256 hasattr(algoClass, "algoType"):
5257 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5258 if not self.defaultAlgoType and \
5259 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5260 self.defaultAlgoType = algoClass.algoType
5261 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5263 # Create a copy of self and assign mesh to the copy
5264 def copy(self, mesh):
5265 other = algoCreator()
5266 other.defaultAlgoType = self.defaultAlgoType
5267 other.algoTypeToClass = self.algoTypeToClass
5271 # Create an instance of algorithm
5272 def __call__(self,algo="",geom=0,*args):
5273 algoType = self.defaultAlgoType
5274 for arg in args + (algo,geom):
5275 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5277 if isinstance( arg, str ) and arg:
5279 if not algoType and self.algoTypeToClass:
5280 algoType = list(self.algoTypeToClass.keys())[0]
5281 if algoType in self.algoTypeToClass:
5282 #print "Create algo",algoType
5283 return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5284 raise RuntimeError("No class found for algo type %s" % algoType)
5287 ## Private class used to substitute and store variable parameters of hypotheses.
5289 class hypMethodWrapper:
5290 def __init__(self, hyp, method):
5292 self.method = method
5293 #print "REBIND:", method.__name__
5296 # call a method of hypothesis with calling SetVarParameter() before
5297 def __call__(self,*args):
5299 return self.method( self.hyp, *args ) # hypothesis method with no args
5301 #print "MethWrapper.__call__",self.method.__name__, args
5303 parsed = ParseParameters(*args) # replace variables with their values
5304 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5305 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5306 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5307 # maybe there is a replaced string arg which is not variable
5308 result = self.method( self.hyp, *args )
5309 except ValueError as detail: # raised by ParseParameters()
5311 result = self.method( self.hyp, *args )
5312 except omniORB.CORBA.BAD_PARAM:
5313 raise ValueError(detail) # wrong variable name
5318 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5320 class genObjUnRegister:
5322 def __init__(self, genObj=None):
5323 self.genObjList = []
5327 def set(self, genObj):
5328 "Store one or a list of of SALOME.GenericObj'es"
5329 if isinstance( genObj, list ):
5330 self.genObjList.extend( genObj )
5332 self.genObjList.append( genObj )
5336 for genObj in self.genObjList:
5337 if genObj and hasattr( genObj, "UnRegister" ):
5341 ## Bind methods creating mesher plug-ins to the Mesh class
5343 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5345 #print "pluginName: ", pluginName
5346 pluginBuilderName = pluginName + "Builder"
5348 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5349 except Exception as e:
5350 from salome_utils import verbose
5351 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
5353 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5354 plugin = eval( pluginBuilderName )
5355 #print " plugin:" , str(plugin)
5357 # add methods creating algorithms to Mesh
5358 for k in dir( plugin ):
5359 if k[0] == '_': continue
5360 algo = getattr( plugin, k )
5361 #print " algo:", str(algo)
5362 if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
5363 #print " meshMethod:" , str(algo.meshMethod)
5364 if not hasattr( Mesh, algo.meshMethod ):
5365 setattr( Mesh, algo.meshMethod, algoCreator() )
5367 getattr( Mesh, algo.meshMethod ).add( algo )