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
87 import omniORB # back compatibility
88 SMESH.MED_V2_1 = omniORB.EnumItem("MED_V2_1", 0) # back compatibility
89 SMESH.MED_V2_2 = omniORB.EnumItem("MED_V2_2", 1) # back compatibility
92 from salome.smesh.smesh_algorithm import Mesh_Algorithm
99 # In case the omniORBpy EnumItem class does not fully support Python 3
100 # (for instance in version 4.2.1-2), the comparison ordering methods must be
104 SMESH.Entity_Triangle < SMESH.Entity_Quadrangle
106 def enumitem_eq(self, other):
108 if isinstance(other, omniORB.EnumItem):
109 if other._parent_id == self._parent_id:
110 return self._v == other._v
112 return self._parent_id == other._parent_id
114 return id(self) == id(other)
116 return id(self) == id(other)
118 def enumitem_lt(self, other):
120 if isinstance(other, omniORB.EnumItem):
121 if other._parent_id == self._parent_id:
122 return self._v < other._v
124 return self._parent_id < other._parent_id
126 return id(self) < id(other)
128 return id(self) < id(other)
130 def enumitem_le(self, other):
132 if isinstance(other, omniORB.EnumItem):
133 if other._parent_id == self._parent_id:
134 return self._v <= other._v
136 return self._parent_id <= other._parent_id
138 return id(self) <= id(other)
140 return id(self) <= id(other)
142 def enumitem_gt(self, other):
144 if isinstance(other, omniORB.EnumItem):
145 if other._parent_id == self._parent_id:
146 return self._v > other._v
148 return self._parent_id > other._parent_id
150 return id(self) > id(other)
152 return id(self) > id(other)
154 def enumitem_ge(self, other):
156 if isinstance(other, omniORB.EnumItem):
157 if other._parent_id == self._parent_id:
158 return self._v >= other._v
160 return self._parent_id >= other._parent_id
162 return id(self) >= id(other)
164 return id(self) >= id(other)
166 omniORB.EnumItem.__eq__ = enumitem_eq
167 omniORB.EnumItem.__lt__ = enumitem_lt
168 omniORB.EnumItem.__le__ = enumitem_le
169 omniORB.EnumItem.__gt__ = enumitem_gt
170 omniORB.EnumItem.__ge__ = enumitem_ge
173 ## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
175 class MeshMeta(type):
176 def __instancecheck__(cls, inst):
177 """Implement isinstance(inst, cls)."""
178 return any(cls.__subclasscheck__(c)
179 for c in {type(inst), inst.__class__})
181 def __subclasscheck__(cls, sub):
182 """Implement issubclass(sub, cls)."""
183 return type.__subclasscheck__(cls, sub) or (cls.__name__ == sub.__name__ and cls.__module__ == sub.__module__)
185 ## @addtogroup l1_auxiliary
188 ## Convert an angle from degrees to radians
189 def DegreesToRadians(AngleInDegrees):
191 return AngleInDegrees * pi / 180.0
193 import salome_notebook
194 notebook = salome_notebook.notebook
195 # Salome notebook variable separator
198 ## Return list of variable values from salome notebook.
199 # The last argument, if is callable, is used to modify values got from notebook
200 def ParseParameters(*args):
205 if args and callable(args[-1]):
206 args, varModifFun = args[:-1], args[-1]
207 for parameter in args:
209 Parameters += str(parameter) + var_separator
211 if isinstance(parameter,str):
212 # check if there is an inexistent variable name
213 if not notebook.isVariable(parameter):
214 raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
215 parameter = notebook.get(parameter)
218 parameter = varModifFun(parameter)
221 Result.append(parameter)
224 Parameters = Parameters[:-1]
225 Result.append( Parameters )
226 Result.append( hasVariables )
229 ## Parse parameters while converting variables to radians
230 def ParseAngles(*args):
231 return ParseParameters( *( args + (DegreesToRadians, )))
233 ## Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
234 # Parameters are stored in PointStruct.parameters attribute
235 def __initPointStruct(point,*args):
236 point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
238 SMESH.PointStruct.__init__ = __initPointStruct
240 ## Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
241 # Parameters are stored in AxisStruct.parameters attribute
242 def __initAxisStruct(ax,*args):
244 raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
245 ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
247 SMESH.AxisStruct.__init__ = __initAxisStruct
249 smeshPrecisionConfusion = 1.e-07
250 ## Compare real values using smeshPrecisionConfusion as tolerance
251 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
252 if abs(val1 - val2) < tol:
258 ## Return object name
262 if isinstance(obj, SALOMEDS._objref_SObject):
266 ior = salome.orb.object_to_string(obj)
270 sobj = salome.myStudy.FindObjectIOR(ior)
272 return sobj.GetName()
273 if hasattr(obj, "GetName"):
274 # unknown CORBA object, having GetName() method
277 # unknown CORBA object, no GetName() method
280 if hasattr(obj, "GetName"):
281 # unknown non-CORBA object, having GetName() method
284 raise RuntimeError("Null or invalid object")
286 ## Print error message if a hypothesis was not assigned.
287 def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
289 hypType = "algorithm"
291 hypType = "hypothesis"
294 if hasattr( status, "__getitem__" ):
295 status, reason = status[0], status[1]
296 if status == HYP_UNKNOWN_FATAL:
297 reason = "for unknown reason"
298 elif status == HYP_INCOMPATIBLE:
299 reason = "this hypothesis mismatches the algorithm"
300 elif status == HYP_NOTCONFORM:
301 reason = "a non-conform mesh would be built"
302 elif status == HYP_ALREADY_EXIST:
303 if isAlgo: return # it does not influence anything
304 reason = hypType + " of the same dimension is already assigned to this shape"
305 elif status == HYP_BAD_DIM:
306 reason = hypType + " mismatches the shape"
307 elif status == HYP_CONCURENT:
308 reason = "there are concurrent hypotheses on sub-shapes"
309 elif status == HYP_BAD_SUBSHAPE:
310 reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
311 elif status == HYP_BAD_GEOMETRY:
312 reason = "the algorithm is not applicable to this geometry"
313 elif status == HYP_HIDDEN_ALGO:
314 reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
315 elif status == HYP_HIDING_ALGO:
316 reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
317 elif status == HYP_NEED_SHAPE:
318 reason = "algorithm can't work without shape"
319 elif status == HYP_INCOMPAT_HYPS:
325 where = '"%s"' % geomName
327 meshName = GetName( mesh )
328 if meshName and meshName != NO_NAME:
329 where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
330 if status < HYP_UNKNOWN_FATAL and where:
331 print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
333 print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
335 print('"%s" was not assigned : %s' %( hypName, reason ))
338 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
339 def AssureGeomPublished(mesh, geom, name=''):
340 if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
342 if not geom.GetStudyEntry():
344 if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
345 # for all groups SubShapeName() return "Compound_-1"
346 name = mesh.geompyD.SubShapeName(geom, mesh.geom)
348 name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
350 mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
353 ## Return the first vertex of a geometrical edge by ignoring orientation
354 def FirstVertexOnCurve(mesh, edge):
355 vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
357 raise TypeError("Given object has no vertices")
358 if len( vv ) == 1: return vv[0]
359 v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
360 xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
361 xyz1 = mesh.geompyD.PointCoordinates( vv[0] )
362 xyz2 = mesh.geompyD.PointCoordinates( vv[1] )
365 dist1 += abs( xyz[i] - xyz1[i] )
366 dist2 += abs( xyz[i] - xyz2[i] )
372 ## Return a long value from enumeration
373 def EnumToLong(theItem):
376 # end of l1_auxiliary
380 # Warning: smeshInst is a singleton
386 ## This class allows to create, load or manipulate meshes.
387 # It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
388 # It also has methods to get infos and measure meshes.
389 class smeshBuilder(SMESH._objref_SMESH_Gen):
391 # MirrorType enumeration
392 POINT = SMESH_MeshEditor.POINT
393 AXIS = SMESH_MeshEditor.AXIS
394 PLANE = SMESH_MeshEditor.PLANE
396 # Smooth_Method enumeration
397 LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
398 CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
400 PrecisionConfusion = smeshPrecisionConfusion
402 # TopAbs_State enumeration
403 [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
405 # Methods of splitting a hexahedron into tetrahedra
406 Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
408 def __new__(cls, *args):
412 #print "==== __new__", engine, smeshInst, doLcc
414 if smeshInst is None:
415 # smesh engine is either retrieved from engine, or created
417 # Following test avoids a recursive loop
419 if smeshInst is not None:
420 # smesh engine not created: existing engine found
424 # FindOrLoadComponent called:
425 # 1. CORBA resolution of server
426 # 2. the __new__ method is called again
427 #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
428 smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
430 # FindOrLoadComponent not called
431 if smeshInst is None:
432 # smeshBuilder instance is created from lcc.FindOrLoadComponent
433 #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
434 smeshInst = super(smeshBuilder,cls).__new__(cls)
436 # smesh engine not created: existing engine found
437 #print "==== existing ", engine, smeshInst, doLcc
439 #print "====1 ", smeshInst
442 #print "====2 ", smeshInst
445 def __init__(self, *args):
447 #print "--------------- smeshbuilder __init__ ---", created
450 SMESH._objref_SMESH_Gen.__init__(self, *args)
452 ## Dump component to the Python script
453 # This method overrides IDL function to allow default values for the parameters.
454 # @ingroup l1_auxiliary
455 def DumpPython(self, theIsPublished=True, theIsMultiFile=True):
456 return SMESH._objref_SMESH_Gen.DumpPython(self, theIsPublished, theIsMultiFile)
458 ## Set mode of DumpPython(), \a historical or \a snapshot.
459 # In the \a historical mode, the Python Dump script includes all commands
460 # performed by SMESH engine. In the \a snapshot mode, commands
461 # relating to objects removed from the Study are excluded from the script
462 # as well as commands not influencing the current state of meshes
463 # @ingroup l1_auxiliary
464 def SetDumpPythonHistorical(self, isHistorical):
465 if isHistorical: val = "true"
467 SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
469 ## Set Geometry component
470 # @ingroup l1_auxiliary
471 def init_smesh(self,isPublished = True,geompyD = None):
473 self.UpdateStudy(geompyD)
476 notebook.myStudy = salome.myStudy
478 ## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
479 # or a mesh wrapping a CORBA mesh given as a parameter.
480 # @param obj either (1) a CORBA mesh (SMESH._objref_SMESH_Mesh) got e.g. by calling
481 # salome.myStudy.FindObjectID("0:1:2:3").GetObject() or
482 # (2) a Geometrical object for meshing or
484 # @param name the name for the new mesh.
485 # @return an instance of Mesh class.
486 # @ingroup l2_construct
487 def Mesh(self, obj=0, name=0):
488 if isinstance(obj,str):
490 return Mesh(self,self.geompyD,obj,name)
492 ## Return a string representation of the color.
493 # To be used with filters.
494 # @param c color value (SALOMEDS.Color)
495 # @ingroup l1_auxiliary
496 def ColorToString(self,c):
498 if isinstance(c, SALOMEDS.Color):
499 val = "%s;%s;%s" % (c.R, c.G, c.B)
500 elif isinstance(c, str):
503 raise ValueError("Color value should be of string or SALOMEDS.Color type")
506 ## Get PointStruct from vertex
507 # @param theVertex a GEOM object(vertex)
508 # @return SMESH.PointStruct
509 # @ingroup l1_auxiliary
510 def GetPointStruct(self,theVertex):
511 [x, y, z] = self.geompyD.PointCoordinates(theVertex)
512 return PointStruct(x,y,z)
514 ## Get DirStruct from vector
515 # @param theVector a GEOM object(vector)
516 # @return SMESH.DirStruct
517 # @ingroup l1_auxiliary
518 def GetDirStruct(self,theVector):
519 vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
520 if(len(vertices) != 2):
521 print("Error: vector object is incorrect.")
523 p1 = self.geompyD.PointCoordinates(vertices[0])
524 p2 = self.geompyD.PointCoordinates(vertices[1])
525 pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
526 dirst = DirStruct(pnt)
529 ## Make DirStruct from a triplet
530 # @param x,y,z vector components
531 # @return SMESH.DirStruct
532 # @ingroup l1_auxiliary
533 def MakeDirStruct(self,x,y,z):
534 pnt = PointStruct(x,y,z)
535 return DirStruct(pnt)
537 ## Get AxisStruct from object
538 # @param theObj a GEOM object (line or plane)
539 # @return SMESH.AxisStruct
540 # @ingroup l1_auxiliary
541 def GetAxisStruct(self,theObj):
543 edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
546 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
547 vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
548 vertex1 = self.geompyD.PointCoordinates(vertex1)
549 vertex2 = self.geompyD.PointCoordinates(vertex2)
550 vertex3 = self.geompyD.PointCoordinates(vertex3)
551 vertex4 = self.geompyD.PointCoordinates(vertex4)
552 v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
553 v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
554 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] ]
555 axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
556 axis._mirrorType = SMESH.SMESH_MeshEditor.PLANE
557 elif len(edges) == 1:
558 vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
559 p1 = self.geompyD.PointCoordinates( vertex1 )
560 p2 = self.geompyD.PointCoordinates( vertex2 )
561 axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
562 axis._mirrorType = SMESH.SMESH_MeshEditor.AXIS
563 elif theObj.GetShapeType() == GEOM.VERTEX:
564 x,y,z = self.geompyD.PointCoordinates( theObj )
565 axis = AxisStruct( x,y,z, 1,0,0,)
566 axis._mirrorType = SMESH.SMESH_MeshEditor.POINT
569 # From SMESH_Gen interface:
570 # ------------------------
572 ## Set the given name to the object
573 # @param obj the object to rename
574 # @param name a new object name
575 # @ingroup l1_auxiliary
576 def SetName(self, obj, name):
577 if isinstance( obj, Mesh ):
579 elif isinstance( obj, Mesh_Algorithm ):
580 obj = obj.GetAlgorithm()
581 ior = salome.orb.object_to_string(obj)
582 SMESH._objref_SMESH_Gen.SetName(self, ior, name)
584 ## Set the current mode
585 # @ingroup l1_auxiliary
586 def SetEmbeddedMode( self,theMode ):
587 SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
589 ## Get the current mode
590 # @ingroup l1_auxiliary
591 def IsEmbeddedMode(self):
592 return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
594 ## Update the current study. Calling UpdateStudy() allows to
595 # update meshes at switching GEOM->SMESH
596 # @ingroup l1_auxiliary
597 def UpdateStudy( self, geompyD = None ):
600 from salome.geom import geomBuilder
601 geompyD = geomBuilder.geom
604 self.SetGeomEngine(geompyD)
605 SMESH._objref_SMESH_Gen.UpdateStudy(self)
606 sb = salome.myStudy.NewBuilder()
607 sc = salome.myStudy.FindComponent("SMESH")
608 if sc: sb.LoadWith(sc, self)
611 ## Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to
612 # switch OFF publishing in the Study of mesh objects.
613 # @ingroup l1_auxiliary
614 def SetEnablePublish( self, theIsEnablePublish ):
615 #self.SetEnablePublish(theIsEnablePublish)
616 SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
618 notebook = salome_notebook.NoteBook( theIsEnablePublish )
620 ## Create a Mesh object importing data from the given UNV file
621 # @return an instance of Mesh class
623 def CreateMeshesFromUNV( self,theFileName ):
624 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
625 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
628 ## Create a Mesh object(s) importing data from the given MED file
629 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
631 def CreateMeshesFromMED( self,theFileName ):
632 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
633 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
634 return aMeshes, aStatus
636 ## Create a Mesh object(s) importing data from the given SAUV file
637 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
639 def CreateMeshesFromSAUV( self,theFileName ):
640 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
641 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
642 return aMeshes, aStatus
644 ## Create a Mesh object importing data from the given STL file
645 # @return an instance of Mesh class
647 def CreateMeshesFromSTL( self, theFileName ):
648 aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
649 aMesh = Mesh(self, self.geompyD, aSmeshMesh)
652 ## Create Mesh objects importing data from the given CGNS file
653 # @return a tuple ( list of Mesh class instances, SMESH.DriverMED_ReadStatus )
655 def CreateMeshesFromCGNS( self, theFileName ):
656 aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
657 aMeshes = [ Mesh(self, self.geompyD, m) for m in aSmeshMeshes ]
658 return aMeshes, aStatus
660 ## Create a Mesh object importing data from the given GMF file.
661 # GMF files must have .mesh extension for the ASCII format and .meshb for
663 # @return [ an instance of Mesh class, SMESH.ComputeError ]
665 def CreateMeshesFromGMF( self, theFileName ):
666 aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
669 if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
670 return Mesh(self, self.geompyD, aSmeshMesh), error
672 ## Concatenate the given meshes into one mesh. All groups of input meshes will be
673 # present in the new mesh.
674 # @param meshes the meshes, sub-meshes and groups to combine into one mesh
675 # @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
676 # @param mergeNodesAndElements if true, equal nodes and elements are merged
677 # @param mergeTolerance tolerance for merging nodes
678 # @param allGroups forces creation of groups corresponding to every input mesh
679 # @param name name of a new mesh
680 # @return an instance of Mesh class
681 # @ingroup l1_creating
682 def Concatenate( self, meshes, uniteIdenticalGroups,
683 mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
685 if not meshes: return None
686 for i,m in enumerate(meshes):
687 if isinstance(m, Mesh):
688 meshes[i] = m.GetMesh()
689 mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
690 meshes[0].SetParameters(Parameters)
692 aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
693 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
695 aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
696 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
697 aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
700 ## Create a mesh by copying a part of another mesh.
701 # @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
702 # to copy nodes or elements not contained in any mesh object,
703 # pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
704 # @param meshName a name of the new mesh
705 # @param toCopyGroups to create in the new mesh groups the copied elements belongs to
706 # @param toKeepIDs to preserve order of the copied elements or not
707 # @return an instance of Mesh class
708 # @ingroup l1_creating
709 def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
710 if (isinstance( meshPart, Mesh )):
711 meshPart = meshPart.GetMesh()
712 mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
713 return Mesh(self, self.geompyD, mesh)
715 ## Return IDs of sub-shapes
716 # @return the list of integer values
717 # @ingroup l1_auxiliary
718 def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
719 return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
721 ## Create a pattern mapper.
722 # @return an instance of SMESH_Pattern
724 # <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
725 # @ingroup l1_modifying
726 def GetPattern(self):
727 return SMESH._objref_SMESH_Gen.GetPattern(self)
729 ## Set number of segments per diagonal of boundary box of geometry, by which
730 # default segment length of appropriate 1D hypotheses is defined in GUI.
731 # Default value is 10.
732 # @ingroup l1_auxiliary
733 def SetBoundaryBoxSegmentation(self, nbSegments):
734 SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
736 # Filtering. Auxiliary functions:
737 # ------------------------------
739 ## Create an empty criterion
740 # @return SMESH.Filter.Criterion
741 # @ingroup l1_controls
742 def GetEmptyCriterion(self):
743 Type = EnumToLong(FT_Undefined)
744 Compare = EnumToLong(FT_Undefined)
748 UnaryOp = EnumToLong(FT_Undefined)
749 BinaryOp = EnumToLong(FT_Undefined)
752 Precision = -1 ##@1e-07
753 return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
754 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
756 ## Create a criterion by the given parameters
757 # \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
758 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
759 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
760 # Type SMESH.FunctorType._items in the Python Console to see all values.
761 # Note that the items starting from FT_LessThan are not suitable for CritType.
762 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
763 # @param Threshold the threshold value (range of ids as string, shape, numeric)
764 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
765 # @param BinaryOp a binary logical operation SMESH.FT_LogicalAND, SMESH.FT_LogicalOR or
767 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
768 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
769 # @return SMESH.Filter.Criterion
771 # <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
772 # @ingroup l1_controls
773 def GetCriterion(self,elementType,
775 Compare = FT_EqualTo,
777 UnaryOp=FT_Undefined,
778 BinaryOp=FT_Undefined,
780 if not CritType in SMESH.FunctorType._items:
781 raise TypeError("CritType should be of SMESH.FunctorType")
782 aCriterion = self.GetEmptyCriterion()
783 aCriterion.TypeOfElement = elementType
784 aCriterion.Type = EnumToLong(CritType)
785 aCriterion.Tolerance = Tolerance
787 aThreshold = Threshold
789 if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
790 aCriterion.Compare = EnumToLong(Compare)
791 elif Compare == "=" or Compare == "==":
792 aCriterion.Compare = EnumToLong(FT_EqualTo)
794 aCriterion.Compare = EnumToLong(FT_LessThan)
796 aCriterion.Compare = EnumToLong(FT_MoreThan)
797 elif Compare != FT_Undefined:
798 aCriterion.Compare = EnumToLong(FT_EqualTo)
801 if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
802 FT_BelongToCylinder, FT_LyingOnGeom]:
803 # Check that Threshold is GEOM object
804 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
805 aCriterion.ThresholdStr = GetName(aThreshold)
806 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
807 if not aCriterion.ThresholdID:
808 name = aCriterion.ThresholdStr
810 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
811 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
812 # or a name of GEOM object
813 elif isinstance( aThreshold, str ):
814 aCriterion.ThresholdStr = aThreshold
816 raise TypeError("The Threshold should be a shape.")
817 if isinstance(UnaryOp,float):
818 aCriterion.Tolerance = UnaryOp
819 UnaryOp = FT_Undefined
821 elif CritType == FT_BelongToMeshGroup:
822 # Check that Threshold is a group
823 if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
824 if aThreshold.GetType() != elementType:
825 raise ValueError("Group type mismatches Element type")
826 aCriterion.ThresholdStr = aThreshold.GetName()
827 aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
828 study = salome.myStudy
830 so = study.FindObjectIOR( aCriterion.ThresholdID )
834 aCriterion.ThresholdID = entry
836 raise TypeError("The Threshold should be a Mesh Group")
837 elif CritType == FT_RangeOfIds:
838 # Check that Threshold is string
839 if isinstance(aThreshold, str):
840 aCriterion.ThresholdStr = aThreshold
842 raise TypeError("The Threshold should be a string.")
843 elif CritType == FT_CoplanarFaces:
844 # Check the Threshold
845 if isinstance(aThreshold, int):
846 aCriterion.ThresholdID = str(aThreshold)
847 elif isinstance(aThreshold, str):
850 raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
851 aCriterion.ThresholdID = aThreshold
853 raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
854 elif CritType == FT_ConnectedElements:
855 # Check the Threshold
856 if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
857 aCriterion.ThresholdID = aThreshold.GetStudyEntry()
858 if not aCriterion.ThresholdID:
859 name = aThreshold.GetName()
861 name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
862 aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
863 elif isinstance(aThreshold, int): # node id
864 aCriterion.Threshold = aThreshold
865 elif isinstance(aThreshold, list): # 3 point coordinates
866 if len( aThreshold ) < 3:
867 raise ValueError("too few point coordinates, must be 3")
868 aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
869 elif isinstance(aThreshold, str):
870 if aThreshold.isdigit():
871 aCriterion.Threshold = aThreshold # node id
873 aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
875 raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
876 "or a list of point coordinates and not '%s'"%aThreshold)
877 elif CritType == FT_ElemGeomType:
878 # Check the Threshold
880 aCriterion.Threshold = EnumToLong(aThreshold)
881 assert( aThreshold in SMESH.GeometryType._items )
883 if isinstance(aThreshold, int):
884 aCriterion.Threshold = aThreshold
886 raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
889 elif CritType == FT_EntityType:
890 # Check the Threshold
892 aCriterion.Threshold = EnumToLong(aThreshold)
893 assert( aThreshold in SMESH.EntityType._items )
895 if isinstance(aThreshold, int):
896 aCriterion.Threshold = aThreshold
898 raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
902 elif CritType == FT_GroupColor:
903 # Check the Threshold
905 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
907 raise TypeError("The threshold value should be of SALOMEDS.Color type")
909 elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
910 FT_LinearOrQuadratic, FT_BadOrientedVolume,
911 FT_BareBorderFace, FT_BareBorderVolume,
912 FT_OverConstrainedFace, FT_OverConstrainedVolume,
913 FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
914 # At this point the Threshold is unnecessary
915 if aThreshold == FT_LogicalNOT:
916 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
917 elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
918 aCriterion.BinaryOp = aThreshold
922 aThreshold = float(aThreshold)
923 aCriterion.Threshold = aThreshold
925 raise TypeError("The Threshold should be a number.")
928 if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
929 aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
931 if Threshold in [FT_LogicalAND, FT_LogicalOR]:
932 aCriterion.BinaryOp = EnumToLong(Threshold)
934 if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
935 aCriterion.BinaryOp = EnumToLong(UnaryOp)
937 if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
938 aCriterion.BinaryOp = EnumToLong(BinaryOp)
942 ## Create a filter with the given parameters
943 # @param elementType the type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
944 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
945 # Type SMESH.FunctorType._items in the Python Console to see all values.
946 # Note that the items starting from FT_LessThan are not suitable for CritType.
947 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
948 # @param Threshold the threshold value (range of ids as string, shape, numeric)
949 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
950 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
951 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces and SMESH.FT_EqualNodes criteria
952 # @param mesh the mesh to initialize the filter with
953 # @return SMESH_Filter
955 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
956 # @ingroup l1_controls
957 def GetFilter(self,elementType,
958 CritType=FT_Undefined,
961 UnaryOp=FT_Undefined,
964 aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
965 aFilterMgr = self.CreateFilterManager()
966 aFilter = aFilterMgr.CreateFilter()
968 aCriteria.append(aCriterion)
969 aFilter.SetCriteria(aCriteria)
971 if isinstance( mesh, Mesh ): aFilter.SetMesh( mesh.GetMesh() )
972 else : aFilter.SetMesh( mesh )
973 aFilterMgr.UnRegister()
976 ## Create a filter from criteria
977 # @param criteria a list of criteria
978 # @param binOp binary operator used when binary operator of criteria is undefined
979 # @return SMESH_Filter
981 # <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
982 # @ingroup l1_controls
983 def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
984 for i in range( len( criteria ) - 1 ):
985 if criteria[i].BinaryOp == EnumToLong( SMESH.FT_Undefined ):
986 criteria[i].BinaryOp = EnumToLong( binOp )
987 aFilterMgr = self.CreateFilterManager()
988 aFilter = aFilterMgr.CreateFilter()
989 aFilter.SetCriteria(criteria)
990 aFilterMgr.UnRegister()
993 ## Create a numerical functor by its type
994 # @param theCriterion functor type - an item of SMESH.FunctorType enumeration.
995 # Type SMESH.FunctorType._items in the Python Console to see all items.
996 # Note that not all items correspond to numerical functors.
997 # @return SMESH_NumericalFunctor
998 # @ingroup l1_controls
999 def GetFunctor(self,theCriterion):
1000 if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
1002 aFilterMgr = self.CreateFilterManager()
1004 if theCriterion == FT_AspectRatio:
1005 functor = aFilterMgr.CreateAspectRatio()
1006 elif theCriterion == FT_AspectRatio3D:
1007 functor = aFilterMgr.CreateAspectRatio3D()
1008 elif theCriterion == FT_Warping:
1009 functor = aFilterMgr.CreateWarping()
1010 elif theCriterion == FT_MinimumAngle:
1011 functor = aFilterMgr.CreateMinimumAngle()
1012 elif theCriterion == FT_Taper:
1013 functor = aFilterMgr.CreateTaper()
1014 elif theCriterion == FT_Skew:
1015 functor = aFilterMgr.CreateSkew()
1016 elif theCriterion == FT_Area:
1017 functor = aFilterMgr.CreateArea()
1018 elif theCriterion == FT_Volume3D:
1019 functor = aFilterMgr.CreateVolume3D()
1020 elif theCriterion == FT_MaxElementLength2D:
1021 functor = aFilterMgr.CreateMaxElementLength2D()
1022 elif theCriterion == FT_MaxElementLength3D:
1023 functor = aFilterMgr.CreateMaxElementLength3D()
1024 elif theCriterion == FT_MultiConnection:
1025 functor = aFilterMgr.CreateMultiConnection()
1026 elif theCriterion == FT_MultiConnection2D:
1027 functor = aFilterMgr.CreateMultiConnection2D()
1028 elif theCriterion == FT_Length:
1029 functor = aFilterMgr.CreateLength()
1030 elif theCriterion == FT_Length2D:
1031 functor = aFilterMgr.CreateLength2D()
1032 elif theCriterion == FT_NodeConnectivityNumber:
1033 functor = aFilterMgr.CreateNodeConnectivityNumber()
1034 elif theCriterion == FT_BallDiameter:
1035 functor = aFilterMgr.CreateBallDiameter()
1037 print("Error: given parameter is not numerical functor type.")
1038 aFilterMgr.UnRegister()
1041 ## Create hypothesis
1042 # @param theHType mesh hypothesis type (string)
1043 # @param theLibName mesh plug-in library name
1044 # @return created hypothesis instance
1045 def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
1046 hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
1048 if isinstance( hyp, SMESH._objref_SMESH_Algo ):
1051 # wrap hypothesis methods
1052 #print "HYPOTHESIS", theHType
1053 for meth_name in dir( hyp.__class__ ):
1054 if not meth_name.startswith("Get") and \
1055 not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
1056 method = getattr ( hyp.__class__, meth_name )
1057 if callable(method):
1058 setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
1062 ## Get the mesh statistic
1063 # @return dictionary "element type" - "count of elements"
1064 # @ingroup l1_meshinfo
1065 def GetMeshInfo(self, obj):
1066 if isinstance( obj, Mesh ):
1069 if hasattr(obj, "GetMeshInfo"):
1070 values = obj.GetMeshInfo()
1071 for i in range(EnumToLong(SMESH.Entity_Last)):
1072 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
1076 ## Get minimum distance between two objects
1078 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1079 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1081 # @param src1 first source object
1082 # @param src2 second source object
1083 # @param id1 node/element id from the first source
1084 # @param id2 node/element id from the second (or first) source
1085 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1086 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1087 # @return minimum distance value
1088 # @sa GetMinDistance()
1089 # @ingroup l1_measurements
1090 def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1091 result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
1095 result = result.value
1098 ## Get measure structure specifying minimum distance data between two objects
1100 # If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
1101 # If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
1103 # @param src1 first source object
1104 # @param src2 second source object
1105 # @param id1 node/element id from the first source
1106 # @param id2 node/element id from the second (or first) source
1107 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
1108 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
1109 # @return Measure structure or None if input data is invalid
1111 # @ingroup l1_measurements
1112 def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
1113 if isinstance(src1, Mesh): src1 = src1.mesh
1114 if isinstance(src2, Mesh): src2 = src2.mesh
1115 if src2 is None and id2 != 0: src2 = src1
1116 if not hasattr(src1, "_narrow"): return None
1117 src1 = src1._narrow(SMESH.SMESH_IDSource)
1118 if not src1: return None
1119 unRegister = genObjUnRegister()
1122 e = m.GetMeshEditor()
1124 src1 = e.MakeIDSource([id1], SMESH.FACE)
1126 src1 = e.MakeIDSource([id1], SMESH.NODE)
1127 unRegister.set( src1 )
1129 if hasattr(src2, "_narrow"):
1130 src2 = src2._narrow(SMESH.SMESH_IDSource)
1131 if src2 and id2 != 0:
1133 e = m.GetMeshEditor()
1135 src2 = e.MakeIDSource([id2], SMESH.FACE)
1137 src2 = e.MakeIDSource([id2], SMESH.NODE)
1138 unRegister.set( src2 )
1141 aMeasurements = self.CreateMeasurements()
1142 unRegister.set( aMeasurements )
1143 result = aMeasurements.MinDistance(src1, src2)
1146 ## Get bounding box of the specified object(s)
1147 # @param objects single source object or list of source objects
1148 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
1149 # @sa GetBoundingBox()
1150 # @ingroup l1_measurements
1151 def BoundingBox(self, objects):
1152 result = self.GetBoundingBox(objects)
1156 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
1159 ## Get measure structure specifying bounding box data of the specified object(s)
1160 # @param objects single source object or list of source objects
1161 # @return Measure structure
1163 # @ingroup l1_measurements
1164 def GetBoundingBox(self, objects):
1165 if isinstance(objects, tuple):
1166 objects = list(objects)
1167 if not isinstance(objects, list):
1171 if isinstance(o, Mesh):
1172 srclist.append(o.mesh)
1173 elif hasattr(o, "_narrow"):
1174 src = o._narrow(SMESH.SMESH_IDSource)
1175 if src: srclist.append(src)
1178 aMeasurements = self.CreateMeasurements()
1179 result = aMeasurements.BoundingBox(srclist)
1180 aMeasurements.UnRegister()
1183 ## Get sum of lengths of all 1D elements in the mesh object.
1184 # @param obj mesh, submesh or group
1185 # @return sum of lengths of all 1D elements
1186 # @ingroup l1_measurements
1187 def GetLength(self, obj):
1188 if isinstance(obj, Mesh): obj = obj.mesh
1189 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1190 aMeasurements = self.CreateMeasurements()
1191 value = aMeasurements.Length(obj)
1192 aMeasurements.UnRegister()
1195 ## Get sum of areas of all 2D elements in the mesh object.
1196 # @param obj mesh, submesh or group
1197 # @return sum of areas of all 2D elements
1198 # @ingroup l1_measurements
1199 def GetArea(self, obj):
1200 if isinstance(obj, Mesh): obj = obj.mesh
1201 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1202 aMeasurements = self.CreateMeasurements()
1203 value = aMeasurements.Area(obj)
1204 aMeasurements.UnRegister()
1207 ## Get sum of volumes of all 3D elements in the mesh object.
1208 # @param obj mesh, submesh or group
1209 # @return sum of volumes of all 3D elements
1210 # @ingroup l1_measurements
1211 def GetVolume(self, obj):
1212 if isinstance(obj, Mesh): obj = obj.mesh
1213 if isinstance(obj, Mesh_Algorithm): obj = obj.GetSubMesh()
1214 aMeasurements = self.CreateMeasurements()
1215 value = aMeasurements.Volume(obj)
1216 aMeasurements.UnRegister()
1219 pass # end of class smeshBuilder
1222 #Registering the new proxy for SMESH_Gen
1223 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1225 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1226 # interface to create or load meshes.
1231 # salome.salome_init()
1232 # from salome.smesh import smeshBuilder
1233 # smesh = smeshBuilder.New()
1235 # @param isPublished If False, the notebool will not be used.
1236 # @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1237 # @return smeshBuilder instance
1239 def New( isPublished = True, instance=None):
1241 Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1242 interface to create or load meshes.
1246 salome.salome_init()
1247 from salome.smesh import smeshBuilder
1248 smesh = smeshBuilder.New()
1251 isPublished If False, the notebool will not be used.
1252 instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
1254 smeshBuilder instance
1262 smeshInst = smeshBuilder()
1263 assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1264 smeshInst.init_smesh(isPublished)
1268 # Public class: Mesh
1269 # ==================
1271 ## This class allows defining and managing a mesh.
1272 # It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1273 # It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1274 # new nodes and elements and by changing the existing entities), to get information
1275 # about a mesh and to export a mesh in different formats.
1276 class Mesh(metaclass=MeshMeta):
1283 # Create a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1284 # sets the GUI name of this mesh to \a name.
1285 # @param smeshpyD an instance of smeshBuilder class
1286 # @param geompyD an instance of geomBuilder class
1287 # @param obj Shape to be meshed or SMESH_Mesh object
1288 # @param name Study name of the mesh
1289 # @ingroup l2_construct
1290 def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1291 self.smeshpyD = smeshpyD
1292 self.geompyD = geompyD
1297 if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1300 # publish geom of mesh (issue 0021122)
1301 if not self.geom.GetStudyEntry():
1305 geo_name = name + " shape"
1307 geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1308 geompyD.addToStudy( self.geom, geo_name )
1309 self.SetMesh( self.smeshpyD.CreateMesh(self.geom) )
1311 elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1314 self.SetMesh( self.smeshpyD.CreateEmptyMesh() )
1316 self.smeshpyD.SetName(self.mesh, name)
1318 self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1321 self.geom = self.mesh.GetShapeToMesh()
1323 self.editor = self.mesh.GetMeshEditor()
1324 self.functors = [None] * EnumToLong(SMESH.FT_Undefined)
1326 # set self to algoCreator's
1327 for attrName in dir(self):
1328 attr = getattr( self, attrName )
1329 if isinstance( attr, algoCreator ):
1330 setattr( self, attrName, attr.copy( self ))
1335 ## Destructor. Clean-up resources
1338 #self.mesh.UnRegister()
1342 ## Initialize the Mesh object from an instance of SMESH_Mesh interface
1343 # @param theMesh a SMESH_Mesh object
1344 # @ingroup l2_construct
1345 def SetMesh(self, theMesh):
1346 # do not call Register() as this prevents mesh servant deletion at closing study
1347 #if self.mesh: self.mesh.UnRegister()
1350 #self.mesh.Register()
1351 self.geom = self.mesh.GetShapeToMesh()
1354 ## Return the mesh, that is an instance of SMESH_Mesh interface
1355 # @return a SMESH_Mesh object
1356 # @ingroup l2_construct
1360 ## Get the name of the mesh
1361 # @return the name of the mesh as a string
1362 # @ingroup l2_construct
1364 name = GetName(self.GetMesh())
1367 ## Set a name to the mesh
1368 # @param name a new name of the mesh
1369 # @ingroup l2_construct
1370 def SetName(self, name):
1371 self.smeshpyD.SetName(self.GetMesh(), name)
1373 ## Get a sub-mesh object associated to a \a geom geometrical object.
1374 # @param geom a geometrical object (shape)
1375 # @param name a name for the sub-mesh in the Object Browser
1376 # @return an object of type SMESH.SMESH_subMesh, representing a part of mesh,
1377 # which lies on the given shape
1379 # The sub-mesh object gives access to the IDs of nodes and elements.
1380 # The sub-mesh object has the following methods:
1381 # - SMESH.SMESH_subMesh.GetNumberOfElements()
1382 # - SMESH.SMESH_subMesh.GetNumberOfNodes( all )
1383 # - SMESH.SMESH_subMesh.GetElementsId()
1384 # - SMESH.SMESH_subMesh.GetElementsByType( ElementType )
1385 # - SMESH.SMESH_subMesh.GetNodesId()
1386 # - SMESH.SMESH_subMesh.GetSubShape()
1387 # - SMESH.SMESH_subMesh.GetFather()
1388 # - SMESH.SMESH_subMesh.GetId()
1389 # @note A sub-mesh is implicitly created when a sub-shape is specified at
1390 # creating an algorithm, for example: <code>algo1D = mesh.Segment(geom=Edge_1) </code>
1391 # creates a sub-mesh on @c Edge_1 and assign Wire Discretization algorithm to it.
1392 # The created sub-mesh can be retrieved from the algorithm:
1393 # <code>submesh = algo1D.GetSubMesh()</code>
1394 # @ingroup l2_submeshes
1395 def GetSubMesh(self, geom, name):
1396 AssureGeomPublished( self, geom, name )
1397 submesh = self.mesh.GetSubMesh( geom, name )
1400 ## Return the shape associated to the mesh
1401 # @return a GEOM_Object
1402 # @ingroup l2_construct
1406 ## Associate the given shape to the mesh (entails the recreation of the mesh)
1407 # @param geom the shape to be meshed (GEOM_Object)
1408 # @ingroup l2_construct
1409 def SetShape(self, geom):
1410 self.mesh = self.smeshpyD.CreateMesh(geom)
1412 ## Load mesh from the study after opening the study
1416 ## Return true if the hypotheses are defined well
1417 # @param theSubObject a sub-shape of a mesh shape
1418 # @return True or False
1419 # @ingroup l2_construct
1420 def IsReadyToCompute(self, theSubObject):
1421 return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1423 ## Return errors of hypotheses definition.
1424 # The list of errors is empty if everything is OK.
1425 # @param theSubObject a sub-shape of a mesh shape
1426 # @return a list of errors
1427 # @ingroup l2_construct
1428 def GetAlgoState(self, theSubObject):
1429 return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1431 ## Return a geometrical object on which the given element was built.
1432 # The returned geometrical object, if not nil, is either found in the
1433 # study or published by this method with the given name
1434 # @param theElementID the id of the mesh element
1435 # @param theGeomName the user-defined name of the geometrical object
1436 # @return GEOM::GEOM_Object instance
1437 # @ingroup l1_meshinfo
1438 def GetGeometryByMeshElement(self, theElementID, theGeomName):
1439 return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1441 ## Return the mesh dimension depending on the dimension of the underlying shape
1442 # or, if the mesh is not based on any shape, basing on deimension of elements
1443 # @return mesh dimension as an integer value [0,3]
1444 # @ingroup l1_meshinfo
1445 def MeshDimension(self):
1446 if self.mesh.HasShapeToMesh():
1447 shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1448 if len( shells ) > 0 :
1450 elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1452 elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1457 if self.NbVolumes() > 0: return 3
1458 if self.NbFaces() > 0: return 2
1459 if self.NbEdges() > 0: return 1
1462 ## Evaluate size of prospective mesh on a shape
1463 # @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1464 # To know predicted number of e.g. edges, inquire it this way
1465 # Evaluate()[ EnumToLong( Entity_Edge )]
1466 # @ingroup l2_construct
1467 def Evaluate(self, geom=0):
1468 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1470 geom = self.mesh.GetShapeToMesh()
1473 return self.smeshpyD.Evaluate(self.mesh, geom)
1476 ## Compute the mesh and return the status of the computation
1477 # @param geom geomtrical shape on which mesh data should be computed
1478 # @param discardModifs if True and the mesh has been edited since
1479 # a last total re-compute and that may prevent successful partial re-compute,
1480 # then the mesh is cleaned before Compute()
1481 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1482 # @return True or False
1483 # @ingroup l2_construct
1484 def Compute(self, geom=0, discardModifs=False, refresh=False):
1485 if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1487 geom = self.mesh.GetShapeToMesh()
1492 if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1494 ok = self.smeshpyD.Compute(self.mesh, geom)
1495 except SALOME.SALOME_Exception as ex:
1496 print("Mesh computation failed, exception caught:")
1497 print(" ", ex.details.text)
1500 print("Mesh computation failed, exception caught:")
1501 traceback.print_exc()
1505 # Treat compute errors
1506 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1508 for err in computeErrors:
1509 if self.mesh.HasShapeToMesh():
1510 shapeText = " on %s" % self.GetSubShapeName( err.subShapeID )
1512 stdErrors = ["OK", #COMPERR_OK
1513 "Invalid input mesh", #COMPERR_BAD_INPUT_MESH
1514 "std::exception", #COMPERR_STD_EXCEPTION
1515 "OCC exception", #COMPERR_OCC_EXCEPTION
1516 "..", #COMPERR_SLM_EXCEPTION
1517 "Unknown exception", #COMPERR_EXCEPTION
1518 "Memory allocation problem", #COMPERR_MEMORY_PB
1519 "Algorithm failed", #COMPERR_ALGO_FAILED
1520 "Unexpected geometry", #COMPERR_BAD_SHAPE
1521 "Warning", #COMPERR_WARNING
1522 "Computation cancelled",#COMPERR_CANCELED
1523 "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1525 if err.code < len(stdErrors): errText = stdErrors[err.code]
1527 errText = "code %s" % -err.code
1528 if errText: errText += ". "
1529 errText += err.comment
1530 if allReasons: allReasons += "\n"
1532 allReasons += '- "%s"%s - %s' %(err.algoName, shapeText, errText)
1534 allReasons += '- "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1538 errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1540 if err.isGlobalAlgo:
1548 reason = '%s %sD algorithm is missing' % (glob, dim)
1549 elif err.state == HYP_MISSING:
1550 reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1551 % (glob, dim, name, dim))
1552 elif err.state == HYP_NOTCONFORM:
1553 reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1554 elif err.state == HYP_BAD_PARAMETER:
1555 reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1556 % ( glob, dim, name ))
1557 elif err.state == HYP_BAD_GEOMETRY:
1558 reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1559 'geometry' % ( glob, dim, name ))
1560 elif err.state == HYP_HIDDEN_ALGO:
1561 reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1562 'algorithm of upper dimension generating %sD mesh'
1563 % ( glob, dim, name, glob, dim ))
1565 reason = ("For unknown reason. "
1566 "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1568 if allReasons: allReasons += "\n"
1569 allReasons += "- " + reason
1571 if not ok or allReasons != "":
1572 msg = '"' + GetName(self.mesh) + '"'
1573 if ok: msg += " has been computed with warnings"
1574 else: msg += " has not been computed"
1575 if allReasons != "": msg += ":"
1580 if salome.sg.hasDesktop():
1581 if not isinstance( refresh, list): # not a call from subMesh.Compute()
1582 smeshgui = salome.ImportComponentGUI("SMESH")
1584 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1585 if refresh: salome.sg.updateObjBrowser()
1589 ## Return a list of error messages (SMESH.ComputeError) of the last Compute()
1590 # @ingroup l2_construct
1591 def GetComputeErrors(self, shape=0 ):
1593 shape = self.mesh.GetShapeToMesh()
1594 return self.smeshpyD.GetComputeErrors( self.mesh, shape )
1596 ## Return a name of a sub-shape by its ID
1597 # @param subShapeID a unique ID of a sub-shape
1598 # @return a string describing the sub-shape; possible variants:
1599 # - "Face_12" (published sub-shape)
1600 # - FACE #3 (not published sub-shape)
1601 # - sub-shape #3 (invalid sub-shape ID)
1602 # - #3 (error in this function)
1603 # @ingroup l1_auxiliary
1604 def GetSubShapeName(self, subShapeID ):
1605 if not self.mesh.HasShapeToMesh():
1609 mainIOR = salome.orb.object_to_string( self.GetShape() )
1611 mainSO = s.FindObjectIOR(mainIOR)
1614 shapeText = '"%s"' % mainSO.GetName()
1615 subIt = s.NewChildIterator(mainSO)
1617 subSO = subIt.Value()
1619 obj = subSO.GetObject()
1620 if not obj: continue
1621 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1624 ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1627 if ids == subShapeID:
1628 shapeText = '"%s"' % subSO.GetName()
1630 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1632 shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1634 shapeText = 'sub-shape #%s' % (subShapeID)
1636 shapeText = "#%s" % (subShapeID)
1639 ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1640 # error of an algorithm
1641 # @param publish if @c True, the returned groups will be published in the study
1642 # @return a list of GEOM groups each named after a failed algorithm
1643 # @ingroup l2_construct
1644 def GetFailedShapes(self, publish=False):
1647 computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1648 for err in computeErrors:
1649 shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1650 if not shape: continue
1651 if err.algoName in algo2shapes:
1652 algo2shapes[ err.algoName ].append( shape )
1654 algo2shapes[ err.algoName ] = [ shape ]
1658 for algoName, shapes in list(algo2shapes.items()):
1660 groupType = EnumToLong( shapes[0].GetShapeType() )
1661 otherTypeShapes = []
1663 group = self.geompyD.CreateGroup( self.geom, groupType )
1664 for shape in shapes:
1665 if shape.GetShapeType() == shapes[0].GetShapeType():
1666 sameTypeShapes.append( shape )
1668 otherTypeShapes.append( shape )
1669 self.geompyD.UnionList( group, sameTypeShapes )
1671 group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1673 group.SetName( algoName )
1674 groups.append( group )
1675 shapes = otherTypeShapes
1678 for group in groups:
1679 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1682 ## Return sub-mesh objects list in meshing order
1683 # @return list of lists of sub-meshes
1684 # @ingroup l2_construct
1685 def GetMeshOrder(self):
1686 return self.mesh.GetMeshOrder()
1688 ## Set order in which concurrent sub-meshes should be meshed
1689 # @param submeshes list of lists of sub-meshes
1690 # @ingroup l2_construct
1691 def SetMeshOrder(self, submeshes):
1692 return self.mesh.SetMeshOrder(submeshes)
1694 ## Remove all nodes and elements generated on geometry. Imported elements remain.
1695 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1696 # @ingroup l2_construct
1697 def Clear(self, refresh=False):
1699 if ( salome.sg.hasDesktop() ):
1700 smeshgui = salome.ImportComponentGUI("SMESH")
1702 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1703 if refresh: salome.sg.updateObjBrowser()
1705 ## Remove all nodes and elements of indicated shape
1706 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1707 # @param geomId the ID of a sub-shape to remove elements on
1708 # @ingroup l2_submeshes
1709 def ClearSubMesh(self, geomId, refresh=False):
1710 self.mesh.ClearSubMesh(geomId)
1711 if salome.sg.hasDesktop():
1712 smeshgui = salome.ImportComponentGUI("SMESH")
1714 smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1715 if refresh: salome.sg.updateObjBrowser()
1717 ## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1718 # @param fineness [0.0,1.0] defines mesh fineness
1719 # @return True or False
1720 # @ingroup l3_algos_basic
1721 def AutomaticTetrahedralization(self, fineness=0):
1722 dim = self.MeshDimension()
1724 self.RemoveGlobalHypotheses()
1725 self.Segment().AutomaticLength(fineness)
1727 self.Triangle().LengthFromEdges()
1732 return self.Compute()
1734 ## Compute an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1735 # @param fineness [0.0, 1.0] defines mesh fineness
1736 # @return True or False
1737 # @ingroup l3_algos_basic
1738 def AutomaticHexahedralization(self, fineness=0):
1739 dim = self.MeshDimension()
1740 # assign the hypotheses
1741 self.RemoveGlobalHypotheses()
1742 self.Segment().AutomaticLength(fineness)
1749 return self.Compute()
1751 ## Assign a hypothesis
1752 # @param hyp a hypothesis to assign
1753 # @param geom a subhape of mesh geometry
1754 # @return SMESH.Hypothesis_Status
1755 # @ingroup l2_editing
1756 def AddHypothesis(self, hyp, geom=0):
1757 if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1758 hyp, geom = geom, hyp
1759 if isinstance( hyp, Mesh_Algorithm ):
1760 hyp = hyp.GetAlgorithm()
1765 geom = self.mesh.GetShapeToMesh()
1768 if self.mesh.HasShapeToMesh():
1769 hyp_type = hyp.GetName()
1770 lib_name = hyp.GetLibName()
1771 # checkAll = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1772 # if checkAll and geom:
1773 # checkAll = geom.GetType() == 37
1775 isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1777 AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1778 status = self.mesh.AddHypothesis(geom, hyp)
1780 status = HYP_BAD_GEOMETRY, ""
1781 hyp_name = GetName( hyp )
1784 geom_name = geom.GetName()
1785 isAlgo = hyp._narrow( SMESH_Algo )
1786 TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1789 ## Return True if an algorithm of hypothesis is assigned to a given shape
1790 # @param hyp a hypothesis to check
1791 # @param geom a subhape of mesh geometry
1792 # @return True of False
1793 # @ingroup l2_editing
1794 def IsUsedHypothesis(self, hyp, geom):
1795 if not hyp: # or not geom
1797 if isinstance( hyp, Mesh_Algorithm ):
1798 hyp = hyp.GetAlgorithm()
1800 hyps = self.GetHypothesisList(geom)
1802 if h.GetId() == hyp.GetId():
1806 ## Unassign a hypothesis
1807 # @param hyp a hypothesis to unassign
1808 # @param geom a sub-shape of mesh geometry
1809 # @return SMESH.Hypothesis_Status
1810 # @ingroup l2_editing
1811 def RemoveHypothesis(self, hyp, geom=0):
1814 if isinstance( hyp, Mesh_Algorithm ):
1815 hyp = hyp.GetAlgorithm()
1821 if self.IsUsedHypothesis( hyp, shape ):
1822 return self.mesh.RemoveHypothesis( shape, hyp )
1823 hypName = GetName( hyp )
1824 geoName = GetName( shape )
1825 print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
1828 ## Get the list of hypotheses added on a geometry
1829 # @param geom a sub-shape of mesh geometry
1830 # @return the sequence of SMESH_Hypothesis
1831 # @ingroup l2_editing
1832 def GetHypothesisList(self, geom):
1833 return self.mesh.GetHypothesisList( geom )
1835 ## Remove all global hypotheses
1836 # @ingroup l2_editing
1837 def RemoveGlobalHypotheses(self):
1838 current_hyps = self.mesh.GetHypothesisList( self.geom )
1839 for hyp in current_hyps:
1840 self.mesh.RemoveHypothesis( self.geom, hyp )
1844 ## Export the mesh in a file in MED format
1845 ## allowing to overwrite the file if it exists or add the exported data to its contents
1846 # @param fileName is the file name
1847 # @param auto_groups boolean parameter for creating/not creating
1848 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1849 # the typical use is auto_groups=False.
1850 # @param overwrite boolean parameter for overwriting/not overwriting the file
1851 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1852 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1853 # - 1D if all mesh nodes lie on OX coordinate axis, or
1854 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1855 # - 3D in the rest cases.<br>
1856 # If @a autoDimension is @c False, the space dimension is always 3.
1857 # @param fields list of GEOM fields defined on the shape to mesh.
1858 # @param geomAssocFields each character of this string means a need to export a
1859 # corresponding field; correspondence between fields and characters is following:
1860 # - 'v' stands for "_vertices _" field;
1861 # - 'e' stands for "_edges _" field;
1862 # - 'f' stands for "_faces _" field;
1863 # - 's' stands for "_solids _" field.
1864 # @ingroup l2_impexp
1865 def ExportMED(self, *args, **kwargs):
1866 # process positional arguments
1867 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1869 auto_groups = args[1] if len(args) > 1 else False
1870 overwrite = args[2] if len(args) > 2 else True
1871 meshPart = args[3] if len(args) > 3 else None
1872 autoDimension = args[4] if len(args) > 4 else True
1873 fields = args[5] if len(args) > 5 else []
1874 geomAssocFields = args[6] if len(args) > 6 else ''
1875 # process keywords arguments
1876 auto_groups = kwargs.get("auto_groups", auto_groups)
1877 overwrite = kwargs.get("overwrite", overwrite)
1878 meshPart = kwargs.get("meshPart", meshPart)
1879 autoDimension = kwargs.get("autoDimension", autoDimension)
1880 fields = kwargs.get("fields", fields)
1881 geomAssocFields = kwargs.get("geomAssocFields", geomAssocFields)
1882 # invoke engine's function
1883 if meshPart or fields or geomAssocFields:
1884 unRegister = genObjUnRegister()
1885 if isinstance( meshPart, list ):
1886 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1887 unRegister.set( meshPart )
1888 self.mesh.ExportPartToMED( meshPart, fileName, auto_groups, overwrite, autoDimension,
1889 fields, geomAssocFields)
1891 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
1893 ## Export the mesh in a file in SAUV format
1894 # @param f is the file name
1895 # @param auto_groups boolean parameter for creating/not creating
1896 # the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1897 # the typical use is auto_groups=false.
1898 # @ingroup l2_impexp
1899 def ExportSAUV(self, f, auto_groups=0):
1900 self.mesh.ExportSAUV(f, auto_groups)
1902 ## Export the mesh in a file in DAT format
1903 # @param f the file name
1904 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1905 # @ingroup l2_impexp
1906 def ExportDAT(self, f, meshPart=None):
1908 unRegister = genObjUnRegister()
1909 if isinstance( meshPart, list ):
1910 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1911 unRegister.set( meshPart )
1912 self.mesh.ExportPartToDAT( meshPart, f )
1914 self.mesh.ExportDAT(f)
1916 ## Export the mesh in a file in UNV format
1917 # @param f the file name
1918 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1919 # @ingroup l2_impexp
1920 def ExportUNV(self, f, meshPart=None):
1922 unRegister = genObjUnRegister()
1923 if isinstance( meshPart, list ):
1924 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1925 unRegister.set( meshPart )
1926 self.mesh.ExportPartToUNV( meshPart, f )
1928 self.mesh.ExportUNV(f)
1930 ## Export the mesh in a file in STL format
1931 # @param f the file name
1932 # @param ascii defines the file encoding
1933 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1934 # @ingroup l2_impexp
1935 def ExportSTL(self, f, ascii=1, meshPart=None):
1937 unRegister = genObjUnRegister()
1938 if isinstance( meshPart, list ):
1939 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1940 unRegister.set( meshPart )
1941 self.mesh.ExportPartToSTL( meshPart, f, ascii )
1943 self.mesh.ExportSTL(f, ascii)
1945 ## Export the mesh in a file in CGNS format
1946 # @param f is the file name
1947 # @param overwrite boolean parameter for overwriting/not overwriting the file
1948 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1949 # @ingroup l2_impexp
1950 def ExportCGNS(self, f, overwrite=1, meshPart=None):
1951 unRegister = genObjUnRegister()
1952 if isinstance( meshPart, list ):
1953 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1954 unRegister.set( meshPart )
1955 if isinstance( meshPart, Mesh ):
1956 meshPart = meshPart.mesh
1958 meshPart = self.mesh
1959 self.mesh.ExportCGNS(meshPart, f, overwrite)
1961 ## Export the mesh in a file in GMF format.
1962 # GMF files must have .mesh extension for the ASCII format and .meshb for
1963 # the bynary format. Other extensions are not allowed.
1964 # @param f is the file name
1965 # @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1966 # @ingroup l2_impexp
1967 def ExportGMF(self, f, meshPart=None):
1968 unRegister = genObjUnRegister()
1969 if isinstance( meshPart, list ):
1970 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1971 unRegister.set( meshPart )
1972 if isinstance( meshPart, Mesh ):
1973 meshPart = meshPart.mesh
1975 meshPart = self.mesh
1976 self.mesh.ExportGMF(meshPart, f, True)
1978 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
1979 # Export the mesh in a file in MED format
1980 # allowing to overwrite the file if it exists or add the exported data to its contents
1981 # @param fileName the file name
1982 # @param opt boolean parameter for creating/not creating
1983 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1984 # @param overwrite boolean parameter for overwriting/not overwriting the file
1985 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
1986 # - 1D if all mesh nodes lie on OX coordinate axis, or
1987 # - 2D if all mesh nodes lie on XOY coordinate plane, or
1988 # - 3D in the rest cases.<br>
1989 # If @a autoDimension is @c False, the space dimension is always 3.
1990 # @ingroup l2_impexp
1991 def ExportToMED(self, *args, **kwargs):
1992 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
1993 # process positional arguments
1994 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
1996 auto_groups = args[1] if len(args) > 1 else False
1997 overwrite = args[2] if len(args) > 2 else True
1998 autoDimension = args[3] if len(args) > 3 else True
1999 # process keywords arguments
2000 auto_groups = kwargs.get("opt", auto_groups) # old keyword name
2001 auto_groups = kwargs.get("auto_groups", auto_groups) # new keyword name
2002 overwrite = kwargs.get("overwrite", overwrite)
2003 autoDimension = kwargs.get("autoDimension", autoDimension)
2004 # invoke engine's function
2005 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2007 ## Deprecated, used only for compatibility! Please, use ExportMED() method instead.
2008 # Export the mesh in a file in MED format
2009 # allowing to overwrite the file if it exists or add the exported data to its contents
2010 # @param fileName the file name
2011 # @param opt boolean parameter for creating/not creating
2012 # the groups Group_On_All_Nodes, Group_On_All_Faces, ...
2013 # @param overwrite boolean parameter for overwriting/not overwriting the file
2014 # @param autoDimension if @c True (default), a space dimension of a MED mesh can be either
2015 # - 1D if all mesh nodes lie on OX coordinate axis, or
2016 # - 2D if all mesh nodes lie on XOY coordinate plane, or
2017 # - 3D in the rest cases.<br>
2018 # If @a autoDimension is @c False, the space dimension is always 3.
2019 # @ingroup l2_impexp
2020 def ExportToMEDX(self, *args, **kwargs):
2021 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
2022 # process positional arguments
2023 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]] # backward compatibility
2025 auto_groups = args[1] if len(args) > 1 else False
2026 overwrite = args[2] if len(args) > 2 else True
2027 autoDimension = args[3] if len(args) > 3 else True
2028 # process keywords arguments
2029 auto_groups = kwargs.get("auto_groups", auto_groups)
2030 overwrite = kwargs.get("overwrite", overwrite)
2031 autoDimension = kwargs.get("autoDimension", autoDimension)
2032 # invoke engine's function
2033 self.mesh.ExportMED(fileName, auto_groups, overwrite, autoDimension)
2035 # Operations with groups:
2036 # ----------------------
2038 ## Create an empty mesh group
2039 # @param elementType the type of elements in the group; either of
2040 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2041 # @param name the name of the mesh group
2042 # @return SMESH_Group
2043 # @ingroup l2_grps_create
2044 def CreateEmptyGroup(self, elementType, name):
2045 return self.mesh.CreateGroup(elementType, name)
2047 ## Create a mesh group based on the geometric object \a grp
2048 # and gives a \a name, \n if this parameter is not defined
2049 # the name is the same as the geometric group name \n
2050 # Note: Works like GroupOnGeom().
2051 # @param grp a geometric group, a vertex, an edge, a face or a solid
2052 # @param name the name of the mesh group
2053 # @return SMESH_GroupOnGeom
2054 # @ingroup l2_grps_create
2055 def Group(self, grp, name=""):
2056 return self.GroupOnGeom(grp, name)
2058 ## Create a mesh group based on the geometrical object \a grp
2059 # and gives a \a name, \n if this parameter is not defined
2060 # the name is the same as the geometrical group name
2061 # @param grp a geometrical group, a vertex, an edge, a face or a solid
2062 # @param name the name of the mesh group
2063 # @param typ the type of elements in the group; either of
2064 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
2065 # automatically detected by the type of the geometry
2066 # @return SMESH_GroupOnGeom
2067 # @ingroup l2_grps_create
2068 def GroupOnGeom(self, grp, name="", typ=None):
2069 AssureGeomPublished( self, grp, name )
2071 name = grp.GetName()
2073 typ = self._groupTypeFromShape( grp )
2074 return self.mesh.CreateGroupFromGEOM(typ, name, grp)
2076 ## Pivate method to get a type of group on geometry
2077 def _groupTypeFromShape( self, shape ):
2078 tgeo = str(shape.GetShapeType())
2079 if tgeo == "VERTEX":
2081 elif tgeo == "EDGE":
2083 elif tgeo == "FACE" or tgeo == "SHELL":
2085 elif tgeo == "SOLID" or tgeo == "COMPSOLID":
2087 elif tgeo == "COMPOUND":
2088 sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
2090 raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
2091 return self._groupTypeFromShape( sub[0] )
2093 raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
2096 ## Create a mesh group with given \a name based on the \a filter which
2097 ## is a special type of group dynamically updating it's contents during
2098 ## mesh modification
2099 # @param typ the type of elements in the group; either of
2100 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2101 # @param name the name of the mesh group
2102 # @param filter the filter defining group contents
2103 # @return SMESH_GroupOnFilter
2104 # @ingroup l2_grps_create
2105 def GroupOnFilter(self, typ, name, filter):
2106 return self.mesh.CreateGroupFromFilter(typ, name, filter)
2108 ## Create a mesh group by the given ids of elements
2109 # @param groupName the name of the mesh group
2110 # @param elementType the type of elements in the group; either of
2111 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2112 # @param elemIDs either the list of ids, group, sub-mesh, or filter
2113 # @return SMESH_Group
2114 # @ingroup l2_grps_create
2115 def MakeGroupByIds(self, groupName, elementType, elemIDs):
2116 group = self.mesh.CreateGroup(elementType, groupName)
2117 if hasattr( elemIDs, "GetIDs" ):
2118 if hasattr( elemIDs, "SetMesh" ):
2119 elemIDs.SetMesh( self.GetMesh() )
2120 group.AddFrom( elemIDs )
2125 ## Create a mesh group by the given conditions
2126 # @param groupName the name of the mesh group
2127 # @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
2128 # @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
2129 # Type SMESH.FunctorType._items in the Python Console to see all values.
2130 # Note that the items starting from FT_LessThan are not suitable for CritType.
2131 # @param Compare belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
2132 # @param Threshold the threshold value (range of ids as string, shape, numeric)
2133 # @param UnaryOp SMESH.FT_LogicalNOT or SMESH.FT_Undefined
2134 # @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
2135 # SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
2136 # @return SMESH_GroupOnFilter
2137 # @ingroup l2_grps_create
2141 CritType=FT_Undefined,
2144 UnaryOp=FT_Undefined,
2146 aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2147 group = self.MakeGroupByCriterion(groupName, aCriterion)
2150 ## Create a mesh group by the given criterion
2151 # @param groupName the name of the mesh group
2152 # @param Criterion the instance of Criterion class
2153 # @return SMESH_GroupOnFilter
2154 # @ingroup l2_grps_create
2155 def MakeGroupByCriterion(self, groupName, Criterion):
2156 return self.MakeGroupByCriteria( groupName, [Criterion] )
2158 ## Create a mesh group by the given criteria (list of criteria)
2159 # @param groupName the name of the mesh group
2160 # @param theCriteria the list of criteria
2161 # @param binOp binary operator used when binary operator of criteria is undefined
2162 # @return SMESH_GroupOnFilter
2163 # @ingroup l2_grps_create
2164 def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2165 aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2166 group = self.MakeGroupByFilter(groupName, aFilter)
2169 ## Create a mesh group by the given filter
2170 # @param groupName the name of the mesh group
2171 # @param theFilter the instance of Filter class
2172 # @return SMESH_GroupOnFilter
2173 # @ingroup l2_grps_create
2174 def MakeGroupByFilter(self, groupName, theFilter):
2175 #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2176 #theFilter.SetMesh( self.mesh )
2177 #group.AddFrom( theFilter )
2178 group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2182 # @ingroup l2_grps_delete
2183 def RemoveGroup(self, group):
2184 self.mesh.RemoveGroup(group)
2186 ## Remove a group with its contents
2187 # @ingroup l2_grps_delete
2188 def RemoveGroupWithContents(self, group):
2189 self.mesh.RemoveGroupWithContents(group)
2191 ## Get the list of groups existing in the mesh in the order
2192 # of creation (starting from the oldest one)
2193 # @param elemType type of elements the groups contain; either of
2194 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2195 # by default groups of elements of all types are returned
2196 # @return a sequence of SMESH_GroupBase
2197 # @ingroup l2_grps_create
2198 def GetGroups(self, elemType = SMESH.ALL):
2199 groups = self.mesh.GetGroups()
2200 if elemType == SMESH.ALL:
2204 if g.GetType() == elemType:
2205 typedGroups.append( g )
2210 ## Get the number of groups existing in the mesh
2211 # @return the quantity of groups as an integer value
2212 # @ingroup l2_grps_create
2214 return self.mesh.NbGroups()
2216 ## Get the list of names of groups existing in the mesh
2217 # @return list of strings
2218 # @ingroup l2_grps_create
2219 def GetGroupNames(self):
2220 groups = self.GetGroups()
2222 for group in groups:
2223 names.append(group.GetName())
2226 ## Find groups by name and type
2227 # @param name name of the group of interest
2228 # @param elemType type of elements the groups contain; either of
2229 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2230 # by default one group of any type of elements is returned
2231 # if elemType == SMESH.ALL then all groups of any type are returned
2232 # @return a list of SMESH_GroupBase's
2233 # @ingroup l2_grps_create
2234 def GetGroupByName(self, name, elemType = None):
2236 for group in self.GetGroups():
2237 if group.GetName() == name:
2238 if elemType is None:
2240 if ( elemType == SMESH.ALL or
2241 group.GetType() == elemType ):
2242 groups.append( group )
2245 ## Produce a union of two groups.
2246 # A new group is created. All mesh elements that are
2247 # present in the initial groups are added to the new one
2248 # @return an instance of SMESH_Group
2249 # @ingroup l2_grps_operon
2250 def UnionGroups(self, group1, group2, name):
2251 return self.mesh.UnionGroups(group1, group2, name)
2253 ## Produce a union list of groups.
2254 # New group is created. All mesh elements that are present in
2255 # initial groups are added to the new one
2256 # @return an instance of SMESH_Group
2257 # @ingroup l2_grps_operon
2258 def UnionListOfGroups(self, groups, name):
2259 return self.mesh.UnionListOfGroups(groups, name)
2261 ## Prodice an intersection of two groups.
2262 # A new group is created. All mesh elements that are common
2263 # for the two initial groups are added to the new one.
2264 # @return an instance of SMESH_Group
2265 # @ingroup l2_grps_operon
2266 def IntersectGroups(self, group1, group2, name):
2267 return self.mesh.IntersectGroups(group1, group2, name)
2269 ## Produce an intersection of groups.
2270 # New group is created. All mesh elements that are present in all
2271 # initial groups simultaneously are added to the new one
2272 # @return an instance of SMESH_Group
2273 # @ingroup l2_grps_operon
2274 def IntersectListOfGroups(self, groups, name):
2275 return self.mesh.IntersectListOfGroups(groups, name)
2277 ## Produce a cut of two groups.
2278 # A new group is created. All mesh elements that are present in
2279 # the main group but are not present in the tool group are added to the new one
2280 # @return an instance of SMESH_Group
2281 # @ingroup l2_grps_operon
2282 def CutGroups(self, main_group, tool_group, name):
2283 return self.mesh.CutGroups(main_group, tool_group, name)
2285 ## Produce a cut of groups.
2286 # A new group is created. All mesh elements that are present in main groups
2287 # but do not present in tool groups are added to the new one
2288 # @return an instance of SMESH_Group
2289 # @ingroup l2_grps_operon
2290 def CutListOfGroups(self, main_groups, tool_groups, name):
2291 return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2294 # Create a standalone group of entities basing on nodes of other groups.
2295 # \param groups - list of reference groups, sub-meshes or filters, of any type.
2296 # \param elemType - a type of elements to include to the new group; either of
2297 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2298 # \param name - a name of the new group.
2299 # \param nbCommonNodes - a criterion of inclusion of an element to the new group
2300 # basing on number of element nodes common with reference \a groups.
2301 # Meaning of possible values are:
2302 # - SMESH.ALL_NODES - include if all nodes are common,
2303 # - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2304 # - SMESH.AT_LEAST_ONE - include if one or more node is common,
2305 # - SMEHS.MAJORITY - include if half of nodes or more are common.
2306 # \param underlyingOnly - if \c True (default), an element is included to the
2307 # new group provided that it is based on nodes of an element of \a groups;
2308 # in this case the reference \a groups are supposed to be of higher dimension
2309 # than \a elemType, which can be useful for example to get all faces lying on
2310 # volumes of the reference \a groups.
2311 # @return an instance of SMESH_Group
2312 # @ingroup l2_grps_operon
2313 def CreateDimGroup(self, groups, elemType, name,
2314 nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2315 if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2317 return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2320 ## Convert group on geom into standalone group
2321 # @ingroup l2_grps_operon
2322 def ConvertToStandalone(self, group):
2323 return self.mesh.ConvertToStandalone(group)
2325 # Get some info about mesh:
2326 # ------------------------
2328 ## Return the log of nodes and elements added or removed
2329 # since the previous clear of the log.
2330 # @param clearAfterGet log is emptied after Get (safe if concurrents access)
2331 # @return list of log_block structures:
2336 # @ingroup l1_auxiliary
2337 def GetLog(self, clearAfterGet):
2338 return self.mesh.GetLog(clearAfterGet)
2340 ## Clear the log of nodes and elements added or removed since the previous
2341 # clear. Must be used immediately after GetLog if clearAfterGet is false.
2342 # @ingroup l1_auxiliary
2344 self.mesh.ClearLog()
2346 ## Toggle auto color mode on the object.
2347 # @param theAutoColor the flag which toggles auto color mode.
2349 # If switched on, a default color of a new group in Create Group dialog is chosen randomly.
2350 # @ingroup l1_grouping
2351 def SetAutoColor(self, theAutoColor):
2352 self.mesh.SetAutoColor(theAutoColor)
2354 ## Get flag of object auto color mode.
2355 # @return True or False
2356 # @ingroup l1_grouping
2357 def GetAutoColor(self):
2358 return self.mesh.GetAutoColor()
2360 ## Get the internal ID
2361 # @return integer value, which is the internal Id of the mesh
2362 # @ingroup l1_auxiliary
2364 return self.mesh.GetId()
2366 ## Check the group names for duplications.
2367 # Consider the maximum group name length stored in MED file.
2368 # @return True or False
2369 # @ingroup l1_grouping
2370 def HasDuplicatedGroupNamesMED(self):
2371 return self.mesh.HasDuplicatedGroupNamesMED()
2373 ## Obtain the mesh editor tool
2374 # @return an instance of SMESH_MeshEditor
2375 # @ingroup l1_modifying
2376 def GetMeshEditor(self):
2379 ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2380 # can be passed as argument to a method accepting mesh, group or sub-mesh
2381 # @param ids list of IDs
2382 # @param elemType type of elements; this parameter is used to distinguish
2383 # IDs of nodes from IDs of elements; by default ids are treated as
2384 # IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2385 # @return an instance of SMESH_IDSource
2386 # @warning call UnRegister() for the returned object as soon as it is no more useful:
2387 # idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2388 # mesh.DoSomething( idSrc )
2389 # idSrc.UnRegister()
2390 # @ingroup l1_auxiliary
2391 def GetIDSource(self, ids, elemType = SMESH.ALL):
2392 if isinstance( ids, int ):
2394 return self.editor.MakeIDSource(ids, elemType)
2397 # Get informations about mesh contents:
2398 # ------------------------------------
2400 ## Get the mesh stattistic
2401 # @return dictionary type element - count of elements
2402 # @ingroup l1_meshinfo
2403 def GetMeshInfo(self, obj = None):
2404 if not obj: obj = self.mesh
2405 return self.smeshpyD.GetMeshInfo(obj)
2407 ## Return the number of nodes in the mesh
2408 # @return an integer value
2409 # @ingroup l1_meshinfo
2411 return self.mesh.NbNodes()
2413 ## Return the number of elements in the mesh
2414 # @return an integer value
2415 # @ingroup l1_meshinfo
2416 def NbElements(self):
2417 return self.mesh.NbElements()
2419 ## Return the number of 0d elements in the mesh
2420 # @return an integer value
2421 # @ingroup l1_meshinfo
2422 def Nb0DElements(self):
2423 return self.mesh.Nb0DElements()
2425 ## Return the number of ball discrete elements in the mesh
2426 # @return an integer value
2427 # @ingroup l1_meshinfo
2429 return self.mesh.NbBalls()
2431 ## Return the number of edges in the mesh
2432 # @return an integer value
2433 # @ingroup l1_meshinfo
2435 return self.mesh.NbEdges()
2437 ## Return the number of edges with the given order in the mesh
2438 # @param elementOrder the order of elements:
2439 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2440 # @return an integer value
2441 # @ingroup l1_meshinfo
2442 def NbEdgesOfOrder(self, elementOrder):
2443 return self.mesh.NbEdgesOfOrder(elementOrder)
2445 ## Return the number of faces in the mesh
2446 # @return an integer value
2447 # @ingroup l1_meshinfo
2449 return self.mesh.NbFaces()
2451 ## Return the number of faces with the given order in the mesh
2452 # @param elementOrder the order of elements:
2453 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2454 # @return an integer value
2455 # @ingroup l1_meshinfo
2456 def NbFacesOfOrder(self, elementOrder):
2457 return self.mesh.NbFacesOfOrder(elementOrder)
2459 ## Return the number of triangles in the mesh
2460 # @return an integer value
2461 # @ingroup l1_meshinfo
2462 def NbTriangles(self):
2463 return self.mesh.NbTriangles()
2465 ## Return the number of triangles with the given order in the mesh
2466 # @param elementOrder is the order of elements:
2467 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2468 # @return an integer value
2469 # @ingroup l1_meshinfo
2470 def NbTrianglesOfOrder(self, elementOrder):
2471 return self.mesh.NbTrianglesOfOrder(elementOrder)
2473 ## Return the number of biquadratic triangles in the mesh
2474 # @return an integer value
2475 # @ingroup l1_meshinfo
2476 def NbBiQuadTriangles(self):
2477 return self.mesh.NbBiQuadTriangles()
2479 ## Return the number of quadrangles in the mesh
2480 # @return an integer value
2481 # @ingroup l1_meshinfo
2482 def NbQuadrangles(self):
2483 return self.mesh.NbQuadrangles()
2485 ## Return the number of quadrangles with the given order in the mesh
2486 # @param elementOrder the order of elements:
2487 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2488 # @return an integer value
2489 # @ingroup l1_meshinfo
2490 def NbQuadranglesOfOrder(self, elementOrder):
2491 return self.mesh.NbQuadranglesOfOrder(elementOrder)
2493 ## Return the number of biquadratic quadrangles in the mesh
2494 # @return an integer value
2495 # @ingroup l1_meshinfo
2496 def NbBiQuadQuadrangles(self):
2497 return self.mesh.NbBiQuadQuadrangles()
2499 ## Return the number of polygons of given order in the mesh
2500 # @param elementOrder the order of elements:
2501 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2502 # @return an integer value
2503 # @ingroup l1_meshinfo
2504 def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2505 return self.mesh.NbPolygonsOfOrder(elementOrder)
2507 ## Return the number of volumes in the mesh
2508 # @return an integer value
2509 # @ingroup l1_meshinfo
2510 def NbVolumes(self):
2511 return self.mesh.NbVolumes()
2513 ## Return the number of volumes with the given order in the mesh
2514 # @param elementOrder the order of elements:
2515 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2516 # @return an integer value
2517 # @ingroup l1_meshinfo
2518 def NbVolumesOfOrder(self, elementOrder):
2519 return self.mesh.NbVolumesOfOrder(elementOrder)
2521 ## Return the number of tetrahedrons in the mesh
2522 # @return an integer value
2523 # @ingroup l1_meshinfo
2525 return self.mesh.NbTetras()
2527 ## Return the number of tetrahedrons with the given order in the mesh
2528 # @param elementOrder the order of elements:
2529 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2530 # @return an integer value
2531 # @ingroup l1_meshinfo
2532 def NbTetrasOfOrder(self, elementOrder):
2533 return self.mesh.NbTetrasOfOrder(elementOrder)
2535 ## Return the number of hexahedrons in the mesh
2536 # @return an integer value
2537 # @ingroup l1_meshinfo
2539 return self.mesh.NbHexas()
2541 ## Return the number of hexahedrons with the given order in the mesh
2542 # @param elementOrder the order of elements:
2543 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2544 # @return an integer value
2545 # @ingroup l1_meshinfo
2546 def NbHexasOfOrder(self, elementOrder):
2547 return self.mesh.NbHexasOfOrder(elementOrder)
2549 ## Return the number of triquadratic hexahedrons in the mesh
2550 # @return an integer value
2551 # @ingroup l1_meshinfo
2552 def NbTriQuadraticHexas(self):
2553 return self.mesh.NbTriQuadraticHexas()
2555 ## Return the number of pyramids in the mesh
2556 # @return an integer value
2557 # @ingroup l1_meshinfo
2558 def NbPyramids(self):
2559 return self.mesh.NbPyramids()
2561 ## Return the number of pyramids with the given order in the mesh
2562 # @param elementOrder the order of elements:
2563 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2564 # @return an integer value
2565 # @ingroup l1_meshinfo
2566 def NbPyramidsOfOrder(self, elementOrder):
2567 return self.mesh.NbPyramidsOfOrder(elementOrder)
2569 ## Return the number of prisms in the mesh
2570 # @return an integer value
2571 # @ingroup l1_meshinfo
2573 return self.mesh.NbPrisms()
2575 ## Return the number of prisms with the given order in the mesh
2576 # @param elementOrder the order of elements:
2577 # SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2578 # @return an integer value
2579 # @ingroup l1_meshinfo
2580 def NbPrismsOfOrder(self, elementOrder):
2581 return self.mesh.NbPrismsOfOrder(elementOrder)
2583 ## Return the number of hexagonal prisms in the mesh
2584 # @return an integer value
2585 # @ingroup l1_meshinfo
2586 def NbHexagonalPrisms(self):
2587 return self.mesh.NbHexagonalPrisms()
2589 ## Return the number of polyhedrons in the mesh
2590 # @return an integer value
2591 # @ingroup l1_meshinfo
2592 def NbPolyhedrons(self):
2593 return self.mesh.NbPolyhedrons()
2595 ## Return the number of submeshes in the mesh
2596 # @return an integer value
2597 # @ingroup l1_meshinfo
2598 def NbSubMesh(self):
2599 return self.mesh.NbSubMesh()
2601 ## Return the list of mesh elements IDs
2602 # @return the list of integer values
2603 # @ingroup l1_meshinfo
2604 def GetElementsId(self):
2605 return self.mesh.GetElementsId()
2607 ## Return the list of IDs of mesh elements with the given type
2608 # @param elementType the required type of elements, either of
2609 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2610 # @return list of integer values
2611 # @ingroup l1_meshinfo
2612 def GetElementsByType(self, elementType):
2613 return self.mesh.GetElementsByType(elementType)
2615 ## Return the list of mesh nodes IDs
2616 # @return the list of integer values
2617 # @ingroup l1_meshinfo
2618 def GetNodesId(self):
2619 return self.mesh.GetNodesId()
2621 # Get the information about mesh elements:
2622 # ------------------------------------
2624 ## Return the type of mesh element
2625 # @return the value from SMESH::ElementType enumeration
2626 # Type SMESH.ElementType._items in the Python Console to see all possible values.
2627 # @ingroup l1_meshinfo
2628 def GetElementType(self, id, iselem=True):
2629 return self.mesh.GetElementType(id, iselem)
2631 ## Return the geometric type of mesh element
2632 # @return the value from SMESH::EntityType enumeration
2633 # Type SMESH.EntityType._items in the Python Console to see all possible values.
2634 # @ingroup l1_meshinfo
2635 def GetElementGeomType(self, id):
2636 return self.mesh.GetElementGeomType(id)
2638 ## Return the shape type of mesh element
2639 # @return the value from SMESH::GeometryType enumeration.
2640 # Type SMESH.GeometryType._items in the Python Console to see all possible values.
2641 # @ingroup l1_meshinfo
2642 def GetElementShape(self, id):
2643 return self.mesh.GetElementShape(id)
2645 ## Return the list of submesh elements IDs
2646 # @param Shape a geom object(sub-shape)
2647 # Shape must be the sub-shape of a ShapeToMesh()
2648 # @return the list of integer values
2649 # @ingroup l1_meshinfo
2650 def GetSubMeshElementsId(self, Shape):
2651 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2652 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2655 return self.mesh.GetSubMeshElementsId(ShapeID)
2657 ## Return the list of submesh nodes IDs
2658 # @param Shape a geom object(sub-shape)
2659 # Shape must be the sub-shape of a ShapeToMesh()
2660 # @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2661 # @return the list of integer values
2662 # @ingroup l1_meshinfo
2663 def GetSubMeshNodesId(self, Shape, all):
2664 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2665 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2668 return self.mesh.GetSubMeshNodesId(ShapeID, all)
2670 ## Return type of elements on given shape
2671 # @param Shape a geom object(sub-shape)
2672 # Shape must be a sub-shape of a ShapeToMesh()
2673 # @return element type
2674 # @ingroup l1_meshinfo
2675 def GetSubMeshElementType(self, Shape):
2676 if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2677 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2680 return self.mesh.GetSubMeshElementType(ShapeID)
2682 ## Get the mesh description
2683 # @return string value
2684 # @ingroup l1_meshinfo
2686 return self.mesh.Dump()
2689 # Get the information about nodes and elements of a mesh by its IDs:
2690 # -----------------------------------------------------------
2692 ## Get XYZ coordinates of a node
2693 # \n If there is no nodes for the given ID - return an empty list
2694 # @return a list of double precision values
2695 # @ingroup l1_meshinfo
2696 def GetNodeXYZ(self, id):
2697 return self.mesh.GetNodeXYZ(id)
2699 ## Return list of IDs of inverse elements for the given node
2700 # \n If there is no node for the given ID - return an empty list
2701 # @return a list of integer values
2702 # @ingroup l1_meshinfo
2703 def GetNodeInverseElements(self, id):
2704 return self.mesh.GetNodeInverseElements(id)
2706 ## Return the position of a node on the shape
2707 # @return SMESH::NodePosition
2708 # @ingroup l1_meshinfo
2709 def GetNodePosition(self,NodeID):
2710 return self.mesh.GetNodePosition(NodeID)
2712 ## Return the position of an element on the shape
2713 # @return SMESH::ElementPosition
2714 # @ingroup l1_meshinfo
2715 def GetElementPosition(self,ElemID):
2716 return self.mesh.GetElementPosition(ElemID)
2718 ## Return the ID of the shape, on which the given node was generated.
2719 # @return an integer value > 0 or -1 if there is no node for the given
2720 # ID or the node is not assigned to any geometry
2721 # @ingroup l1_meshinfo
2722 def GetShapeID(self, id):
2723 return self.mesh.GetShapeID(id)
2725 ## Return the ID of the shape, on which the given element was generated.
2726 # @return an integer value > 0 or -1 if there is no element for the given
2727 # ID or the element is not assigned to any geometry
2728 # @ingroup l1_meshinfo
2729 def GetShapeIDForElem(self,id):
2730 return self.mesh.GetShapeIDForElem(id)
2732 ## Return the number of nodes of the given element
2733 # @return an integer value > 0 or -1 if there is no element for the given ID
2734 # @ingroup l1_meshinfo
2735 def GetElemNbNodes(self, id):
2736 return self.mesh.GetElemNbNodes(id)
2738 ## Return the node ID the given (zero based) index for the given element
2739 # \n If there is no element for the given ID - return -1
2740 # \n If there is no node for the given index - return -2
2741 # @return an integer value
2742 # @ingroup l1_meshinfo
2743 def GetElemNode(self, id, index):
2744 return self.mesh.GetElemNode(id, index)
2746 ## Return the IDs of nodes of the given element
2747 # @return a list of integer values
2748 # @ingroup l1_meshinfo
2749 def GetElemNodes(self, id):
2750 return self.mesh.GetElemNodes(id)
2752 ## Return true if the given node is the medium node in the given quadratic element
2753 # @ingroup l1_meshinfo
2754 def IsMediumNode(self, elementID, nodeID):
2755 return self.mesh.IsMediumNode(elementID, nodeID)
2757 ## Return true if the given node is the medium node in one of quadratic elements
2758 # @param nodeID ID of the node
2759 # @param elementType the type of elements to check a state of the node, either of
2760 # (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2761 # @ingroup l1_meshinfo
2762 def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2763 return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2765 ## Return the number of edges for the given element
2766 # @ingroup l1_meshinfo
2767 def ElemNbEdges(self, id):
2768 return self.mesh.ElemNbEdges(id)
2770 ## Return the number of faces for the given element
2771 # @ingroup l1_meshinfo
2772 def ElemNbFaces(self, id):
2773 return self.mesh.ElemNbFaces(id)
2775 ## Return nodes of given face (counted from zero) for given volumic element.
2776 # @ingroup l1_meshinfo
2777 def GetElemFaceNodes(self,elemId, faceIndex):
2778 return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2780 ## Return three components of normal of given mesh face
2781 # (or an empty array in KO case)
2782 # @ingroup l1_meshinfo
2783 def GetFaceNormal(self, faceId, normalized=False):
2784 return self.mesh.GetFaceNormal(faceId,normalized)
2786 ## Return an element based on all given nodes.
2787 # @ingroup l1_meshinfo
2788 def FindElementByNodes(self, nodes):
2789 return self.mesh.FindElementByNodes(nodes)
2791 ## Return elements including all given nodes.
2792 # @ingroup l1_meshinfo
2793 def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
2794 return self.mesh.GetElementsByNodes( nodes, elemType )
2796 ## Return true if the given element is a polygon
2797 # @ingroup l1_meshinfo
2798 def IsPoly(self, id):
2799 return self.mesh.IsPoly(id)
2801 ## Return true if the given element is quadratic
2802 # @ingroup l1_meshinfo
2803 def IsQuadratic(self, id):
2804 return self.mesh.IsQuadratic(id)
2806 ## Return diameter of a ball discrete element or zero in case of an invalid \a id
2807 # @ingroup l1_meshinfo
2808 def GetBallDiameter(self, id):
2809 return self.mesh.GetBallDiameter(id)
2811 ## Return XYZ coordinates of the barycenter of the given element
2812 # \n If there is no element for the given ID - return an empty list
2813 # @return a list of three double values
2814 # @ingroup l1_meshinfo
2815 def BaryCenter(self, id):
2816 return self.mesh.BaryCenter(id)
2818 ## Pass mesh elements through the given filter and return IDs of fitting elements
2819 # @param theFilter SMESH_Filter
2820 # @return a list of ids
2821 # @ingroup l1_controls
2822 def GetIdsFromFilter(self, theFilter):
2823 theFilter.SetMesh( self.mesh )
2824 return theFilter.GetIDs()
2826 # Get mesh measurements information:
2827 # ------------------------------------
2829 ## Verify whether a 2D mesh element has free edges (edges connected to one face only)\n
2830 # Return a list of special structures (borders).
2831 # @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2832 # @ingroup l1_measurements
2833 def GetFreeBorders(self):
2834 aFilterMgr = self.smeshpyD.CreateFilterManager()
2835 aPredicate = aFilterMgr.CreateFreeEdges()
2836 aPredicate.SetMesh(self.mesh)
2837 aBorders = aPredicate.GetBorders()
2838 aFilterMgr.UnRegister()
2841 ## Get minimum distance between two nodes, elements or distance to the origin
2842 # @param id1 first node/element id
2843 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2844 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2845 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2846 # @return minimum distance value
2847 # @sa GetMinDistance()
2848 # @ingroup l1_measurements
2849 def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2850 aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2851 return aMeasure.value
2853 ## Get measure structure specifying minimum distance data between two objects
2854 # @param id1 first node/element id
2855 # @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2856 # @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2857 # @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2858 # @return Measure structure
2860 # @ingroup l1_measurements
2861 def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2863 id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2865 id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2868 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2870 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2875 aMeasurements = self.smeshpyD.CreateMeasurements()
2876 aMeasure = aMeasurements.MinDistance(id1, id2)
2877 genObjUnRegister([aMeasurements,id1, id2])
2880 ## Get bounding box of the specified object(s)
2881 # @param objects single source object or list of source objects or list of nodes/elements IDs
2882 # @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2883 # @c False specifies that @a objects are nodes
2884 # @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2885 # @sa GetBoundingBox()
2886 # @ingroup l1_measurements
2887 def BoundingBox(self, objects=None, isElem=False):
2888 result = self.GetBoundingBox(objects, isElem)
2892 result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2895 ## Get measure structure specifying bounding box data of the specified object(s)
2896 # @param IDs single source object or list of source objects or list of nodes/elements IDs
2897 # @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2898 # @c False specifies that @a objects are nodes
2899 # @return Measure structure
2901 # @ingroup l1_measurements
2902 def GetBoundingBox(self, IDs=None, isElem=False):
2905 elif isinstance(IDs, tuple):
2907 if not isinstance(IDs, list):
2909 if len(IDs) > 0 and isinstance(IDs[0], int):
2912 unRegister = genObjUnRegister()
2914 if isinstance(o, Mesh):
2915 srclist.append(o.mesh)
2916 elif hasattr(o, "_narrow"):
2917 src = o._narrow(SMESH.SMESH_IDSource)
2918 if src: srclist.append(src)
2920 elif isinstance(o, list):
2922 srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2924 srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2925 unRegister.set( srclist[-1] )
2928 aMeasurements = self.smeshpyD.CreateMeasurements()
2929 unRegister.set( aMeasurements )
2930 aMeasure = aMeasurements.BoundingBox(srclist)
2933 # Mesh edition (SMESH_MeshEditor functionality):
2934 # ---------------------------------------------
2936 ## Remove the elements from the mesh by ids
2937 # @param IDsOfElements is a list of ids of elements to remove
2938 # @return True or False
2939 # @ingroup l2_modif_del
2940 def RemoveElements(self, IDsOfElements):
2941 return self.editor.RemoveElements(IDsOfElements)
2943 ## Remove nodes from mesh by ids
2944 # @param IDsOfNodes is a list of ids of nodes to remove
2945 # @return True or False
2946 # @ingroup l2_modif_del
2947 def RemoveNodes(self, IDsOfNodes):
2948 return self.editor.RemoveNodes(IDsOfNodes)
2950 ## Remove all orphan (free) nodes from mesh
2951 # @return number of the removed nodes
2952 # @ingroup l2_modif_del
2953 def RemoveOrphanNodes(self):
2954 return self.editor.RemoveOrphanNodes()
2956 ## Add a node to the mesh by coordinates
2957 # @return Id of the new node
2958 # @ingroup l2_modif_add
2959 def AddNode(self, x, y, z):
2960 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2961 if hasVars: self.mesh.SetParameters(Parameters)
2962 return self.editor.AddNode( x, y, z)
2964 ## Create a 0D element on a node with given number.
2965 # @param IDOfNode the ID of node for creation of the element.
2966 # @param DuplicateElements to add one more 0D element to a node or not
2967 # @return the Id of the new 0D element
2968 # @ingroup l2_modif_add
2969 def Add0DElement( self, IDOfNode, DuplicateElements=True ):
2970 return self.editor.Add0DElement( IDOfNode, DuplicateElements )
2972 ## Create 0D elements on all nodes of the given elements except those
2973 # nodes on which a 0D element already exists.
2974 # @param theObject an object on whose nodes 0D elements will be created.
2975 # It can be mesh, sub-mesh, group, list of element IDs or a holder
2976 # of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2977 # @param theGroupName optional name of a group to add 0D elements created
2978 # and/or found on nodes of \a theObject.
2979 # @param DuplicateElements to add one more 0D element to a node or not
2980 # @return an object (a new group or a temporary SMESH_IDSource) holding
2981 # IDs of new and/or found 0D elements. IDs of 0D elements
2982 # can be retrieved from the returned object by calling GetIDs()
2983 # @ingroup l2_modif_add
2984 def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
2985 unRegister = genObjUnRegister()
2986 if isinstance( theObject, Mesh ):
2987 theObject = theObject.GetMesh()
2988 elif isinstance( theObject, list ):
2989 theObject = self.GetIDSource( theObject, SMESH.ALL )
2990 unRegister.set( theObject )
2991 return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName, DuplicateElements )
2993 ## Create a ball element on a node with given ID.
2994 # @param IDOfNode the ID of node for creation of the element.
2995 # @param diameter the bal diameter.
2996 # @return the Id of the new ball element
2997 # @ingroup l2_modif_add
2998 def AddBall(self, IDOfNode, diameter):
2999 return self.editor.AddBall( IDOfNode, diameter )
3001 ## Create a linear or quadratic edge (this is determined
3002 # by the number of given nodes).
3003 # @param IDsOfNodes the list of node IDs for creation of the element.
3004 # The order of nodes in this list should correspond to the description
3005 # of MED. \n This description is located by the following link:
3006 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3007 # @return the Id of the new edge
3008 # @ingroup l2_modif_add
3009 def AddEdge(self, IDsOfNodes):
3010 return self.editor.AddEdge(IDsOfNodes)
3012 ## Create a linear or quadratic face (this is determined
3013 # by the number of given nodes).
3014 # @param IDsOfNodes the list of node IDs for creation of the element.
3015 # The order of nodes in this list should correspond to the description
3016 # of MED. \n This description is located by the following link:
3017 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3018 # @return the Id of the new face
3019 # @ingroup l2_modif_add
3020 def AddFace(self, IDsOfNodes):
3021 return self.editor.AddFace(IDsOfNodes)
3023 ## Add a polygonal face to the mesh by the list of node IDs
3024 # @param IdsOfNodes the list of node IDs for creation of the element.
3025 # @return the Id of the new face
3026 # @ingroup l2_modif_add
3027 def AddPolygonalFace(self, IdsOfNodes):
3028 return self.editor.AddPolygonalFace(IdsOfNodes)
3030 ## Add a quadratic polygonal face to the mesh by the list of node IDs
3031 # @param IdsOfNodes the list of node IDs for creation of the element;
3032 # corner nodes follow first.
3033 # @return the Id of the new face
3034 # @ingroup l2_modif_add
3035 def AddQuadPolygonalFace(self, IdsOfNodes):
3036 return self.editor.AddQuadPolygonalFace(IdsOfNodes)
3038 ## Create both simple and quadratic volume (this is determined
3039 # by the number of given nodes).
3040 # @param IDsOfNodes the list of node IDs for creation of the element.
3041 # The order of nodes in this list should correspond to the description
3042 # of MED. \n This description is located by the following link:
3043 # http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
3044 # @return the Id of the new volumic element
3045 # @ingroup l2_modif_add
3046 def AddVolume(self, IDsOfNodes):
3047 return self.editor.AddVolume(IDsOfNodes)
3049 ## Create a volume of many faces, giving nodes for each face.
3050 # @param IdsOfNodes the list of node IDs for volume creation face by face.
3051 # @param Quantities the list of integer values, Quantities[i]
3052 # gives the quantity of nodes in face number i.
3053 # @return the Id of the new volumic element
3054 # @ingroup l2_modif_add
3055 def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
3056 return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
3058 ## Create a volume of many faces, giving the IDs of the existing faces.
3059 # @param IdsOfFaces the list of face IDs for volume creation.
3061 # Note: The created volume will refer only to the nodes
3062 # of the given faces, not to the faces themselves.
3063 # @return the Id of the new volumic element
3064 # @ingroup l2_modif_add
3065 def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
3066 return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
3069 ## @brief Binds a node to a vertex
3070 # @param NodeID a node ID
3071 # @param Vertex a vertex or vertex ID
3072 # @return True if succeed else raises an exception
3073 # @ingroup l2_modif_add
3074 def SetNodeOnVertex(self, NodeID, Vertex):
3075 if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
3076 VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
3080 self.editor.SetNodeOnVertex(NodeID, VertexID)
3081 except SALOME.SALOME_Exception as inst:
3082 raise ValueError(inst.details.text)
3086 ## @brief Stores the node position on an edge
3087 # @param NodeID a node ID
3088 # @param Edge an edge or edge ID
3089 # @param paramOnEdge a parameter on the edge where the node is located
3090 # @return True if succeed else raises an exception
3091 # @ingroup l2_modif_add
3092 def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
3093 if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
3094 EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
3098 self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
3099 except SALOME.SALOME_Exception as inst:
3100 raise ValueError(inst.details.text)
3103 ## @brief Stores node position on a face
3104 # @param NodeID a node ID
3105 # @param Face a face or face ID
3106 # @param u U parameter on the face where the node is located
3107 # @param v V parameter on the face where the node is located
3108 # @return True if succeed else raises an exception
3109 # @ingroup l2_modif_add
3110 def SetNodeOnFace(self, NodeID, Face, u, v):
3111 if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
3112 FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
3116 self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
3117 except SALOME.SALOME_Exception as inst:
3118 raise ValueError(inst.details.text)
3121 ## @brief Binds a node to a solid
3122 # @param NodeID a node ID
3123 # @param Solid a solid or solid ID
3124 # @return True if succeed else raises an exception
3125 # @ingroup l2_modif_add
3126 def SetNodeInVolume(self, NodeID, Solid):
3127 if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
3128 SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
3132 self.editor.SetNodeInVolume(NodeID, SolidID)
3133 except SALOME.SALOME_Exception as inst:
3134 raise ValueError(inst.details.text)
3137 ## @brief Bind an element to a shape
3138 # @param ElementID an element ID
3139 # @param Shape a shape or shape ID
3140 # @return True if succeed else raises an exception
3141 # @ingroup l2_modif_add
3142 def SetMeshElementOnShape(self, ElementID, Shape):
3143 if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
3144 ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
3148 self.editor.SetMeshElementOnShape(ElementID, ShapeID)
3149 except SALOME.SALOME_Exception as inst:
3150 raise ValueError(inst.details.text)
3154 ## Move the node with the given id
3155 # @param NodeID the id of the node
3156 # @param x a new X coordinate
3157 # @param y a new Y coordinate
3158 # @param z a new Z coordinate
3159 # @return True if succeed else False
3160 # @ingroup l2_modif_edit
3161 def MoveNode(self, NodeID, x, y, z):
3162 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3163 if hasVars: self.mesh.SetParameters(Parameters)
3164 return self.editor.MoveNode(NodeID, x, y, z)
3166 ## Find the node closest to a point and moves it to a point location
3167 # @param x the X coordinate of a point
3168 # @param y the Y coordinate of a point
3169 # @param z the Z coordinate of a point
3170 # @param NodeID if specified (>0), the node with this ID is moved,
3171 # otherwise, the node closest to point (@a x,@a y,@a z) is moved
3172 # @return the ID of a node
3173 # @ingroup l2_modif_edit
3174 def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3175 x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3176 if hasVars: self.mesh.SetParameters(Parameters)
3177 return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3179 ## Find the node closest to a point
3180 # @param x the X coordinate of a point
3181 # @param y the Y coordinate of a point
3182 # @param z the Z coordinate of a point
3183 # @return the ID of a node
3184 # @ingroup l1_meshinfo
3185 def FindNodeClosestTo(self, x, y, z):
3186 #preview = self.mesh.GetMeshEditPreviewer()
3187 #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3188 return self.editor.FindNodeClosestTo(x, y, z)
3190 ## Find the elements where a point lays IN or ON
3191 # @param x the X coordinate of a point
3192 # @param y the Y coordinate of a point
3193 # @param z the Z coordinate of a point
3194 # @param elementType type of elements to find; either of
3195 # (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3196 # means elements of any type excluding nodes, discrete and 0D elements.
3197 # @param meshPart a part of mesh (group, sub-mesh) to search within
3198 # @return list of IDs of found elements
3199 # @ingroup l1_meshinfo
3200 def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3202 return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3204 return self.editor.FindElementsByPoint(x, y, z, elementType)
3206 ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3207 # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3208 # UNKNOWN state means that either mesh is wrong or the analysis fails.
3209 # @ingroup l1_meshinfo
3210 def GetPointState(self, x, y, z):
3211 return self.editor.GetPointState(x, y, z)
3213 ## Find the node closest to a point and moves it to a point location
3214 # @param x the X coordinate of a point
3215 # @param y the Y coordinate of a point
3216 # @param z the Z coordinate of a point
3217 # @return the ID of a moved node
3218 # @ingroup l2_modif_edit
3219 def MeshToPassThroughAPoint(self, x, y, z):
3220 return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3222 ## Replace two neighbour triangles sharing Node1-Node2 link
3223 # with the triangles built on the same 4 nodes but having other common link.
3224 # @param NodeID1 the ID of the first node
3225 # @param NodeID2 the ID of the second node
3226 # @return false if proper faces were not found
3227 # @ingroup l2_modif_cutquadr
3228 def InverseDiag(self, NodeID1, NodeID2):
3229 return self.editor.InverseDiag(NodeID1, NodeID2)
3231 ## Replace two neighbour triangles sharing Node1-Node2 link
3232 # with a quadrangle built on the same 4 nodes.
3233 # @param NodeID1 the ID of the first node
3234 # @param NodeID2 the ID of the second node
3235 # @return false if proper faces were not found
3236 # @ingroup l2_modif_unitetri
3237 def DeleteDiag(self, NodeID1, NodeID2):
3238 return self.editor.DeleteDiag(NodeID1, NodeID2)
3240 ## Reorient elements by ids
3241 # @param IDsOfElements if undefined reorients all mesh elements
3242 # @return True if succeed else False
3243 # @ingroup l2_modif_changori
3244 def Reorient(self, IDsOfElements=None):
3245 if IDsOfElements == None:
3246 IDsOfElements = self.GetElementsId()
3247 return self.editor.Reorient(IDsOfElements)
3249 ## Reorient all elements of the object
3250 # @param theObject mesh, submesh or group
3251 # @return True if succeed else False
3252 # @ingroup l2_modif_changori
3253 def ReorientObject(self, theObject):
3254 if ( isinstance( theObject, Mesh )):
3255 theObject = theObject.GetMesh()
3256 return self.editor.ReorientObject(theObject)
3258 ## Reorient faces contained in \a the2DObject.
3259 # @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3260 # @param theDirection is a desired direction of normal of \a theFace.
3261 # It can be either a GEOM vector or a list of coordinates [x,y,z].
3262 # @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3263 # compared with theDirection. It can be either ID of face or a point
3264 # by which the face will be found. The point can be given as either
3265 # a GEOM vertex or a list of point coordinates.
3266 # @return number of reoriented faces
3267 # @ingroup l2_modif_changori
3268 def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3269 unRegister = genObjUnRegister()
3271 if isinstance( the2DObject, Mesh ):
3272 the2DObject = the2DObject.GetMesh()
3273 if isinstance( the2DObject, list ):
3274 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3275 unRegister.set( the2DObject )
3276 # check theDirection
3277 if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3278 theDirection = self.smeshpyD.GetDirStruct( theDirection )
3279 if isinstance( theDirection, list ):
3280 theDirection = self.smeshpyD.MakeDirStruct( *theDirection )
3281 # prepare theFace and thePoint
3282 theFace = theFaceOrPoint
3283 thePoint = PointStruct(0,0,0)
3284 if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3285 thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3287 if isinstance( theFaceOrPoint, list ):
3288 thePoint = PointStruct( *theFaceOrPoint )
3290 if isinstance( theFaceOrPoint, PointStruct ):
3291 thePoint = theFaceOrPoint
3293 return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3295 ## Reorient faces according to adjacent volumes.
3296 # @param the2DObject is a mesh, sub-mesh, group or list of
3297 # either IDs of faces or face groups.
3298 # @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3299 # @param theOutsideNormal to orient faces to have their normals
3300 # pointing either \a outside or \a inside the adjacent volumes.
3301 # @return number of reoriented faces.
3302 # @ingroup l2_modif_changori
3303 def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3304 unRegister = genObjUnRegister()
3306 if not isinstance( the2DObject, list ):
3307 the2DObject = [ the2DObject ]
3308 elif the2DObject and isinstance( the2DObject[0], int ):
3309 the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3310 unRegister.set( the2DObject )
3311 the2DObject = [ the2DObject ]
3312 for i,obj2D in enumerate( the2DObject ):
3313 if isinstance( obj2D, Mesh ):
3314 the2DObject[i] = obj2D.GetMesh()
3315 if isinstance( obj2D, list ):
3316 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3317 unRegister.set( the2DObject[i] )
3319 if isinstance( the3DObject, Mesh ):
3320 the3DObject = the3DObject.GetMesh()
3321 if isinstance( the3DObject, list ):
3322 the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3323 unRegister.set( the3DObject )
3324 return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3326 ## Fuse the neighbouring triangles into quadrangles.
3327 # @param IDsOfElements The triangles to be fused.
3328 # @param theCriterion a numerical functor, in terms of enum SMESH.FunctorType, used to
3329 # applied to possible quadrangles to choose a neighbour to fuse with.
3330 # Type SMESH.FunctorType._items in the Python Console to see all items.
3331 # Note that not all items correspond to numerical functors.
3332 # @param MaxAngle is the maximum angle between element normals at which the fusion
3333 # is still performed; theMaxAngle is mesured in radians.
3334 # Also it could be a name of variable which defines angle in degrees.
3335 # @return TRUE in case of success, FALSE otherwise.
3336 # @ingroup l2_modif_unitetri
3337 def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3338 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3339 self.mesh.SetParameters(Parameters)
3340 if not IDsOfElements:
3341 IDsOfElements = self.GetElementsId()
3342 Functor = self.smeshpyD.GetFunctor(theCriterion)
3343 return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3345 ## Fuse the neighbouring triangles of the object into quadrangles
3346 # @param theObject is mesh, submesh or group
3347 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType,
3348 # applied to possible quadrangles to choose a neighbour to fuse with.
3349 # Type SMESH.FunctorType._items in the Python Console to see all items.
3350 # Note that not all items correspond to numerical functors.
3351 # @param MaxAngle a max angle between element normals at which the fusion
3352 # is still performed; theMaxAngle is mesured in radians.
3353 # @return TRUE in case of success, FALSE otherwise.
3354 # @ingroup l2_modif_unitetri
3355 def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3356 MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3357 self.mesh.SetParameters(Parameters)
3358 if isinstance( theObject, Mesh ):
3359 theObject = theObject.GetMesh()
3360 Functor = self.smeshpyD.GetFunctor(theCriterion)
3361 return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3363 ## Split quadrangles into triangles.
3364 # @param IDsOfElements the faces to be splitted.
3365 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3366 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3367 # value, then quadrangles will be split by the smallest diagonal.
3368 # Type SMESH.FunctorType._items in the Python Console to see all items.
3369 # Note that not all items correspond to numerical functors.
3370 # @return TRUE in case of success, FALSE otherwise.
3371 # @ingroup l2_modif_cutquadr
3372 def QuadToTri (self, IDsOfElements, theCriterion = None):
3373 if IDsOfElements == []:
3374 IDsOfElements = self.GetElementsId()
3375 if theCriterion is None:
3376 theCriterion = FT_MaxElementLength2D
3377 Functor = self.smeshpyD.GetFunctor(theCriterion)
3378 return self.editor.QuadToTri(IDsOfElements, Functor)
3380 ## Split quadrangles into triangles.
3381 # @param theObject the object from which the list of elements is taken,
3382 # this is mesh, submesh or group
3383 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3384 # choose a diagonal for splitting. If @a theCriterion is None, which is a default
3385 # value, then quadrangles will be split by the smallest diagonal.
3386 # Type SMESH.FunctorType._items in the Python Console to see all items.
3387 # Note that not all items correspond to numerical functors.
3388 # @return TRUE in case of success, FALSE otherwise.
3389 # @ingroup l2_modif_cutquadr
3390 def QuadToTriObject (self, theObject, theCriterion = None):
3391 if ( isinstance( theObject, Mesh )):
3392 theObject = theObject.GetMesh()
3393 if theCriterion is None:
3394 theCriterion = FT_MaxElementLength2D
3395 Functor = self.smeshpyD.GetFunctor(theCriterion)
3396 return self.editor.QuadToTriObject(theObject, Functor)
3398 ## Split each of given quadrangles into 4 triangles. A node is added at the center of
3400 # @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3401 # group or a list of face IDs. By default all quadrangles are split
3402 # @ingroup l2_modif_cutquadr
3403 def QuadTo4Tri (self, theElements=[]):
3404 unRegister = genObjUnRegister()
3405 if isinstance( theElements, Mesh ):
3406 theElements = theElements.mesh
3407 elif not theElements:
3408 theElements = self.mesh
3409 elif isinstance( theElements, list ):
3410 theElements = self.GetIDSource( theElements, SMESH.FACE )
3411 unRegister.set( theElements )
3412 return self.editor.QuadTo4Tri( theElements )
3414 ## Split quadrangles into triangles.
3415 # @param IDsOfElements the faces to be splitted
3416 # @param Diag13 is used to choose a diagonal for splitting.
3417 # @return TRUE in case of success, FALSE otherwise.
3418 # @ingroup l2_modif_cutquadr
3419 def SplitQuad (self, IDsOfElements, Diag13):
3420 if IDsOfElements == []:
3421 IDsOfElements = self.GetElementsId()
3422 return self.editor.SplitQuad(IDsOfElements, Diag13)
3424 ## Split quadrangles into triangles.
3425 # @param theObject the object from which the list of elements is taken,
3426 # this is mesh, submesh or group
3427 # @param Diag13 is used to choose a diagonal for splitting.
3428 # @return TRUE in case of success, FALSE otherwise.
3429 # @ingroup l2_modif_cutquadr
3430 def SplitQuadObject (self, theObject, Diag13):
3431 if ( isinstance( theObject, Mesh )):
3432 theObject = theObject.GetMesh()
3433 return self.editor.SplitQuadObject(theObject, Diag13)
3435 ## Find a better splitting of the given quadrangle.
3436 # @param IDOfQuad the ID of the quadrangle to be splitted.
3437 # @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3438 # choose a diagonal for splitting.
3439 # Type SMESH.FunctorType._items in the Python Console to see all items.
3440 # Note that not all items correspond to numerical functors.
3441 # @return 1 if 1-3 diagonal is better, 2 if 2-4
3442 # diagonal is better, 0 if error occurs.
3443 # @ingroup l2_modif_cutquadr
3444 def BestSplit (self, IDOfQuad, theCriterion):
3445 return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3447 ## Split volumic elements into tetrahedrons
3448 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3449 # @param method flags passing splitting method:
3450 # smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3451 # smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3452 # @ingroup l2_modif_cutquadr
3453 def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3454 unRegister = genObjUnRegister()
3455 if isinstance( elems, Mesh ):
3456 elems = elems.GetMesh()
3457 if ( isinstance( elems, list )):
3458 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3459 unRegister.set( elems )
3460 self.editor.SplitVolumesIntoTetra(elems, method)
3463 ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3464 # - bi-quadratic triangle will be split into 3 linear quadrangles;
3465 # - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3466 # - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3467 # Quadratic elements of lower dimension adjacent to the split bi-quadratic element
3468 # will be split in order to keep the mesh conformal.
3469 # @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3470 # if None (default), all bi-quadratic elements will be split
3471 # @ingroup l2_modif_cutquadr
3472 def SplitBiQuadraticIntoLinear(self, elems=None):
3473 unRegister = genObjUnRegister()
3474 if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3475 elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3476 unRegister.set( elems )
3478 elems = [ self.GetMesh() ]
3479 if isinstance( elems, Mesh ):
3480 elems = [ elems.GetMesh() ]
3481 if not isinstance( elems, list ):
3483 self.editor.SplitBiQuadraticIntoLinear( elems )
3485 ## Split hexahedra into prisms
3486 # @param elems either a list of elements or a mesh or a group or a submesh or a filter
3487 # @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3488 # gives a normal vector defining facets to split into triangles.
3489 # @a startHexPoint can be either a triple of coordinates or a vertex.
3490 # @param facetNormal a normal to a facet to split into triangles of a
3491 # hexahedron found by @a startHexPoint.
3492 # @a facetNormal can be either a triple of coordinates or an edge.
3493 # @param method flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3494 # smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3495 # @param allDomains if @c False, only hexahedra adjacent to one closest
3496 # to @a startHexPoint are split, else @a startHexPoint
3497 # is used to find the facet to split in all domains present in @a elems.
3498 # @ingroup l2_modif_cutquadr
3499 def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3500 method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3502 unRegister = genObjUnRegister()
3503 if isinstance( elems, Mesh ):
3504 elems = elems.GetMesh()
3505 if ( isinstance( elems, list )):
3506 elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3507 unRegister.set( elems )
3510 if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3511 startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3512 elif isinstance( startHexPoint, list ):
3513 startHexPoint = SMESH.PointStruct( startHexPoint[0],
3516 if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3517 facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3518 elif isinstance( facetNormal, list ):
3519 facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3522 self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3524 self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3526 ## Split quadrangle faces near triangular facets of volumes
3528 # @ingroup l2_modif_cutquadr
3529 def SplitQuadsNearTriangularFacets(self):
3530 faces_array = self.GetElementsByType(SMESH.FACE)
3531 for face_id in faces_array:
3532 if self.GetElemNbNodes(face_id) == 4: # quadrangle
3533 quad_nodes = self.mesh.GetElemNodes(face_id)
3534 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3535 isVolumeFound = False
3536 for node1_elem in node1_elems:
3537 if not isVolumeFound:
3538 if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3539 nb_nodes = self.GetElemNbNodes(node1_elem)
3540 if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3541 volume_elem = node1_elem
3542 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3543 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3544 if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3545 isVolumeFound = True
3546 if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3547 self.SplitQuad([face_id], False) # diagonal 2-4
3548 elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3549 isVolumeFound = True
3550 self.SplitQuad([face_id], True) # diagonal 1-3
3551 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3552 if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3553 isVolumeFound = True
3554 self.SplitQuad([face_id], True) # diagonal 1-3
3556 ## @brief Splits hexahedrons into tetrahedrons.
3558 # This operation uses pattern mapping functionality for splitting.
3559 # @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3560 # @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3561 # pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3562 # will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3563 # key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3564 # The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3565 # @return TRUE in case of success, FALSE otherwise.
3566 # @ingroup l2_modif_cutquadr
3567 def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3568 # Pattern: 5.---------.6
3573 # (0,0,1) 4.---------.7 * |
3580 # (0,0,0) 0.---------.3
3581 pattern_tetra = "!!! Nb of points: \n 8 \n\
3591 !!! Indices of points of 6 tetras: \n\
3599 pattern = self.smeshpyD.GetPattern()
3600 isDone = pattern.LoadFromFile(pattern_tetra)
3602 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3605 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3606 isDone = pattern.MakeMesh(self.mesh, False, False)
3607 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3609 # split quafrangle faces near triangular facets of volumes
3610 self.SplitQuadsNearTriangularFacets()
3614 ## @brief Split hexahedrons into prisms.
3616 # Uses the pattern mapping functionality for splitting.
3617 # @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3618 # @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3619 # pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3620 # will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3621 # will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3622 # Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3623 # @return TRUE in case of success, FALSE otherwise.
3624 # @ingroup l2_modif_cutquadr
3625 def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3626 # Pattern: 5.---------.6
3631 # (0,0,1) 4.---------.7 |
3638 # (0,0,0) 0.---------.3
3639 pattern_prism = "!!! Nb of points: \n 8 \n\
3649 !!! Indices of points of 2 prisms: \n\
3653 pattern = self.smeshpyD.GetPattern()
3654 isDone = pattern.LoadFromFile(pattern_prism)
3656 print('Pattern.LoadFromFile :', pattern.GetErrorCode())
3659 pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3660 isDone = pattern.MakeMesh(self.mesh, False, False)
3661 if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
3663 # Split quafrangle faces near triangular facets of volumes
3664 self.SplitQuadsNearTriangularFacets()
3669 # @param IDsOfElements the list if ids of elements to smooth
3670 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3671 # Note that nodes built on edges and boundary nodes are always fixed.
3672 # @param MaxNbOfIterations the maximum number of iterations
3673 # @param MaxAspectRatio varies in range [1.0, inf]
3674 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3675 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3676 # @return TRUE in case of success, FALSE otherwise.
3677 # @ingroup l2_modif_smooth
3678 def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3679 MaxNbOfIterations, MaxAspectRatio, Method):
3680 if IDsOfElements == []:
3681 IDsOfElements = self.GetElementsId()
3682 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3683 self.mesh.SetParameters(Parameters)
3684 return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3685 MaxNbOfIterations, MaxAspectRatio, Method)
3687 ## Smooth elements which belong to the given object
3688 # @param theObject the object to smooth
3689 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3690 # Note that nodes built on edges and boundary nodes are always fixed.
3691 # @param MaxNbOfIterations the maximum number of iterations
3692 # @param MaxAspectRatio varies in range [1.0, inf]
3693 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3694 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3695 # @return TRUE in case of success, FALSE otherwise.
3696 # @ingroup l2_modif_smooth
3697 def SmoothObject(self, theObject, IDsOfFixedNodes,
3698 MaxNbOfIterations, MaxAspectRatio, Method):
3699 if ( isinstance( theObject, Mesh )):
3700 theObject = theObject.GetMesh()
3701 return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3702 MaxNbOfIterations, MaxAspectRatio, Method)
3704 ## Parametrically smooth the given elements
3705 # @param IDsOfElements the list if ids of elements to smooth
3706 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3707 # Note that nodes built on edges and boundary nodes are always fixed.
3708 # @param MaxNbOfIterations the maximum number of iterations
3709 # @param MaxAspectRatio varies in range [1.0, inf]
3710 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3711 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3712 # @return TRUE in case of success, FALSE otherwise.
3713 # @ingroup l2_modif_smooth
3714 def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3715 MaxNbOfIterations, MaxAspectRatio, Method):
3716 if IDsOfElements == []:
3717 IDsOfElements = self.GetElementsId()
3718 MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3719 self.mesh.SetParameters(Parameters)
3720 return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3721 MaxNbOfIterations, MaxAspectRatio, Method)
3723 ## Parametrically smooth the elements which belong to the given object
3724 # @param theObject the object to smooth
3725 # @param IDsOfFixedNodes the list of ids of fixed nodes.
3726 # Note that nodes built on edges and boundary nodes are always fixed.
3727 # @param MaxNbOfIterations the maximum number of iterations
3728 # @param MaxAspectRatio varies in range [1.0, inf]
3729 # @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3730 # or Centroidal (smesh.CENTROIDAL_SMOOTH)
3731 # @return TRUE in case of success, FALSE otherwise.
3732 # @ingroup l2_modif_smooth
3733 def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3734 MaxNbOfIterations, MaxAspectRatio, Method):
3735 if ( isinstance( theObject, Mesh )):
3736 theObject = theObject.GetMesh()
3737 return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3738 MaxNbOfIterations, MaxAspectRatio, Method)
3740 ## Convert the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3741 # them with quadratic with the same id.
3742 # @param theForce3d new node creation method:
3743 # 0 - the medium node lies at the geometrical entity from which the mesh element is built
3744 # 1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3745 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3746 # @param theToBiQuad If True, converts the mesh to bi-quadratic
3747 # @return SMESH.ComputeError which can hold a warning
3748 # @ingroup l2_modif_tofromqu
3749 def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3750 if isinstance( theSubMesh, Mesh ):
3751 theSubMesh = theSubMesh.mesh
3753 self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3756 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3758 self.editor.ConvertToQuadratic(theForce3d)
3759 error = self.editor.GetLastError()
3760 if error and error.comment:
3761 print(error.comment)
3764 ## Convert the mesh from quadratic to ordinary,
3765 # deletes old quadratic elements, \n replacing
3766 # them with ordinary mesh elements with the same id.
3767 # @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3768 # @ingroup l2_modif_tofromqu
3769 def ConvertFromQuadratic(self, theSubMesh=None):
3771 self.editor.ConvertFromQuadraticObject(theSubMesh)
3773 return self.editor.ConvertFromQuadratic()
3775 ## Create 2D mesh as skin on boundary faces of a 3D mesh
3776 # @return TRUE if operation has been completed successfully, FALSE otherwise
3777 # @ingroup l2_modif_add
3778 def Make2DMeshFrom3D(self):
3779 return self.editor.Make2DMeshFrom3D()
3781 ## Create missing boundary elements
3782 # @param elements - elements whose boundary is to be checked:
3783 # mesh, group, sub-mesh or list of elements
3784 # if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3785 # @param dimension - defines type of boundary elements to create, either of
3786 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3787 # SMESH.BND_1DFROM3D create mesh edges on all borders of free facets of 3D cells
3788 # @param groupName - a name of group to store created boundary elements in,
3789 # "" means not to create the group
3790 # @param meshName - a name of new mesh to store created boundary elements in,
3791 # "" means not to create the new mesh
3792 # @param toCopyElements - if true, the checked elements will be copied into
3793 # the new mesh else only boundary elements will be copied into the new mesh
3794 # @param toCopyExistingBondary - if true, not only new but also pre-existing
3795 # boundary elements will be copied into the new mesh
3796 # @return tuple (mesh, group) where boundary elements were added to
3797 # @ingroup l2_modif_add
3798 def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3799 toCopyElements=False, toCopyExistingBondary=False):
3800 unRegister = genObjUnRegister()
3801 if isinstance( elements, Mesh ):
3802 elements = elements.GetMesh()
3803 if ( isinstance( elements, list )):
3804 elemType = SMESH.ALL
3805 if elements: elemType = self.GetElementType( elements[0], iselem=True)
3806 elements = self.editor.MakeIDSource(elements, elemType)
3807 unRegister.set( elements )
3808 mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3809 toCopyElements,toCopyExistingBondary)
3810 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3814 # @brief Create missing boundary elements around either the whole mesh or
3815 # groups of elements
3816 # @param dimension - defines type of boundary elements to create, either of
3817 # { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3818 # @param groupName - a name of group to store all boundary elements in,
3819 # "" means not to create the group
3820 # @param meshName - a name of a new mesh, which is a copy of the initial
3821 # mesh + created boundary elements; "" means not to create the new mesh
3822 # @param toCopyAll - if true, the whole initial mesh will be copied into
3823 # the new mesh else only boundary elements will be copied into the new mesh
3824 # @param groups - groups of elements to make boundary around
3825 # @retval tuple( long, mesh, groups )
3826 # long - number of added boundary elements
3827 # mesh - the mesh where elements were added to
3828 # group - the group of boundary elements or None
3830 # @ingroup l2_modif_add
3831 def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3832 toCopyAll=False, groups=[]):
3833 nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3835 if mesh: mesh = self.smeshpyD.Mesh(mesh)
3836 return nb, mesh, group
3838 ## Renumber mesh nodes (Obsolete, does nothing)
3839 # @ingroup l2_modif_renumber
3840 def RenumberNodes(self):
3841 self.editor.RenumberNodes()
3843 ## Renumber mesh elements (Obsole, does nothing)
3844 # @ingroup l2_modif_renumber
3845 def RenumberElements(self):
3846 self.editor.RenumberElements()
3848 ## Private method converting \a arg into a list of SMESH_IdSource's
3849 def _getIdSourceList(self, arg, idType, unRegister):
3850 if arg and isinstance( arg, list ):
3851 if isinstance( arg[0], int ):
3852 arg = self.GetIDSource( arg, idType )
3853 unRegister.set( arg )
3854 elif isinstance( arg[0], Mesh ):
3855 arg[0] = arg[0].GetMesh()
3856 elif isinstance( arg, Mesh ):
3858 if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3862 ## Generate new elements by rotation of the given elements and nodes around the axis
3863 # @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3864 # @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3865 # @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3866 # @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3867 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3868 # which defines angle in degrees
3869 # @param NbOfSteps the number of steps
3870 # @param Tolerance tolerance
3871 # @param MakeGroups forces the generation of new groups from existing ones
3872 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3873 # of all steps, else - size of each step
3874 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3875 # @ingroup l2_modif_extrurev
3876 def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3877 MakeGroups=False, TotalAngle=False):
3878 unRegister = genObjUnRegister()
3879 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3880 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3881 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3883 if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3884 Axis = self.smeshpyD.GetAxisStruct( Axis )
3885 if isinstance( Axis, list ):
3886 Axis = SMESH.AxisStruct( *Axis )
3888 AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3889 NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3890 Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3891 self.mesh.SetParameters(Parameters)
3892 if TotalAngle and NbOfSteps:
3893 AngleInRadians /= NbOfSteps
3894 return self.editor.RotationSweepObjects( nodes, edges, faces,
3895 Axis, AngleInRadians,
3896 NbOfSteps, Tolerance, MakeGroups)
3898 ## Generate new elements by rotation of the elements around the axis
3899 # @param IDsOfElements the list of ids of elements to sweep
3900 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3901 # @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3902 # @param NbOfSteps the number of steps
3903 # @param Tolerance tolerance
3904 # @param MakeGroups forces the generation of new groups from existing ones
3905 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3906 # of all steps, else - size of each step
3907 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3908 # @ingroup l2_modif_extrurev
3909 def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3910 MakeGroups=False, TotalAngle=False):
3911 return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3912 AngleInRadians, NbOfSteps, Tolerance,
3913 MakeGroups, TotalAngle)
3915 ## Generate new elements by rotation of the elements of object around the axis
3916 # @param theObject object which elements should be sweeped.
3917 # It can be a mesh, a sub mesh or a group.
3918 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3919 # @param AngleInRadians the angle of Rotation
3920 # @param NbOfSteps number of steps
3921 # @param Tolerance tolerance
3922 # @param MakeGroups forces the generation of new groups from existing ones
3923 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3924 # of all steps, else - size of each step
3925 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3926 # @ingroup l2_modif_extrurev
3927 def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3928 MakeGroups=False, TotalAngle=False):
3929 return self.RotationSweepObjects( [], theObject, theObject, Axis,
3930 AngleInRadians, NbOfSteps, Tolerance,
3931 MakeGroups, TotalAngle )
3933 ## Generate new elements by rotation of the elements of object around the axis
3934 # @param theObject object which elements should be sweeped.
3935 # It can be a mesh, a sub mesh or a group.
3936 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3937 # @param AngleInRadians the angle of Rotation
3938 # @param NbOfSteps number of steps
3939 # @param Tolerance tolerance
3940 # @param MakeGroups forces the generation of new groups from existing ones
3941 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3942 # of all steps, else - size of each step
3943 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3944 # @ingroup l2_modif_extrurev
3945 def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3946 MakeGroups=False, TotalAngle=False):
3947 return self.RotationSweepObjects([],theObject,[], Axis,
3948 AngleInRadians, NbOfSteps, Tolerance,
3949 MakeGroups, TotalAngle)
3951 ## Generate new elements by rotation of the elements of object around the axis
3952 # @param theObject object which elements should be sweeped.
3953 # It can be a mesh, a sub mesh or a group.
3954 # @param Axis the axis of rotation, AxisStruct or line(geom object)
3955 # @param AngleInRadians the angle of Rotation
3956 # @param NbOfSteps number of steps
3957 # @param Tolerance tolerance
3958 # @param MakeGroups forces the generation of new groups from existing ones
3959 # @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3960 # of all steps, else - size of each step
3961 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3962 # @ingroup l2_modif_extrurev
3963 def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3964 MakeGroups=False, TotalAngle=False):
3965 return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3966 NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3968 ## Generate new elements by extrusion of the given elements and nodes
3969 # @param nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3970 # @param edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3971 # @param faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3972 # @param StepVector vector or DirStruct or 3 vector components, defining
3973 # the direction and value of extrusion for one step (the total extrusion
3974 # length will be NbOfSteps * ||StepVector||)
3975 # @param NbOfSteps the number of steps
3976 # @param MakeGroups forces the generation of new groups from existing ones
3977 # @param scaleFactors optional scale factors to apply during extrusion
3978 # @param linearVariation if @c True, scaleFactors are spread over all @a scaleFactors,
3979 # else scaleFactors[i] is applied to nodes at the i-th extrusion step
3980 # @param basePoint optional scaling center; if not provided, a gravity center of
3981 # nodes and elements being extruded is used as the scaling center.
3983 # - a list of tree components of the point or
3986 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3987 # @ingroup l2_modif_extrurev
3988 # @ref tui_extrusion example
3989 def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False,
3990 scaleFactors=[], linearVariation=False, basePoint=[] ):
3991 unRegister = genObjUnRegister()
3992 nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3993 edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3994 faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3996 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3997 StepVector = self.smeshpyD.GetDirStruct(StepVector)
3998 if isinstance( StepVector, list ):
3999 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4001 if isinstance( basePoint, int):
4002 xyz = self.GetNodeXYZ( basePoint )
4004 raise RuntimeError("Invalid node ID: %s" % basePoint)
4006 if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
4007 basePoint = self.geompyD.PointCoordinates( basePoint )
4009 NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
4010 Parameters = StepVector.PS.parameters + var_separator + Parameters
4011 self.mesh.SetParameters(Parameters)
4013 return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
4014 StepVector, NbOfSteps,
4015 scaleFactors, linearVariation, basePoint,
4019 ## Generate new elements by extrusion of the elements with given ids
4020 # @param IDsOfElements the list of ids of elements or nodes for extrusion
4021 # @param StepVector vector or DirStruct or 3 vector components, defining
4022 # the direction and value of extrusion for one step (the total extrusion
4023 # length will be NbOfSteps * ||StepVector||)
4024 # @param NbOfSteps the number of steps
4025 # @param MakeGroups forces the generation of new groups from existing ones
4026 # @param IsNodes is True if elements with given ids are nodes
4027 # @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4028 # @ingroup l2_modif_extrurev
4029 # @ref tui_extrusion example
4030 def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
4032 if IsNodes: n = IDsOfElements
4033 else : e,f, = IDsOfElements,IDsOfElements
4034 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4036 ## Generate new elements by extrusion along the normal to a discretized surface or wire
4037 # @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh.
4038 # Only faces can be extruded so far. A sub-mesh should be a sub-mesh on geom faces.
4039 # @param StepSize length of one extrusion step (the total extrusion
4040 # length will be \a NbOfSteps * \a StepSize ).
4041 # @param NbOfSteps number of extrusion steps.
4042 # @param ByAverageNormal if True each node is translated by \a StepSize
4043 # along the average of the normal vectors to the faces sharing the node;
4044 # else each node is translated along the same average normal till
4045 # intersection with the plane got by translation of the face sharing
4046 # the node along its own normal by \a StepSize.
4047 # @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
4048 # for every node of \a Elements.
4049 # @param MakeGroups forces generation of new groups from existing ones.
4050 # @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
4051 # is not yet implemented. This parameter is used if \a Elements contains
4052 # both faces and edges, i.e. \a Elements is a Mesh.
4053 # @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
4054 # empty list otherwise.
4055 # @ingroup l2_modif_extrurev
4056 # @ref tui_extrusion example
4057 def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
4058 ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
4059 unRegister = genObjUnRegister()
4060 if isinstance( Elements, Mesh ):
4061 Elements = [ Elements.GetMesh() ]
4062 if isinstance( Elements, list ):
4064 raise RuntimeError("Elements empty!")
4065 if isinstance( Elements[0], int ):
4066 Elements = self.GetIDSource( Elements, SMESH.ALL )
4067 unRegister.set( Elements )
4068 if not isinstance( Elements, list ):
4069 Elements = [ Elements ]
4070 StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
4071 self.mesh.SetParameters(Parameters)
4072 return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
4073 ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
4075 ## Generate new elements by extrusion of the elements or nodes which belong to the object
4076 # @param theObject the object whose elements or nodes should be processed.
4077 # It can be a mesh, a sub-mesh or a group.
4078 # @param StepVector vector or DirStruct or 3 vector components, defining
4079 # the direction and value of extrusion for one step (the total extrusion
4080 # length will be NbOfSteps * ||StepVector||)
4081 # @param NbOfSteps the number of steps
4082 # @param MakeGroups forces the generation of new groups from existing ones
4083 # @param IsNodes is True if elements to extrude are nodes
4084 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4085 # @ingroup l2_modif_extrurev
4086 # @ref tui_extrusion example
4087 def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
4089 if IsNodes: n = theObject
4090 else : e,f, = theObject,theObject
4091 return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
4093 ## Generate new elements by extrusion of edges which belong to the object
4094 # @param theObject object whose 1D elements should be processed.
4095 # It can be a mesh, a sub-mesh or a group.
4096 # @param StepVector vector or DirStruct or 3 vector components, defining
4097 # the direction and value of extrusion for one step (the total extrusion
4098 # length will be NbOfSteps * ||StepVector||)
4099 # @param NbOfSteps the number of steps
4100 # @param MakeGroups to generate new groups from existing ones
4101 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4102 # @ingroup l2_modif_extrurev
4103 # @ref tui_extrusion example
4104 def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4105 return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
4107 ## Generate new elements by extrusion of faces which belong to the object
4108 # @param theObject object whose 2D elements should be processed.
4109 # It can be a mesh, a sub-mesh or a group.
4110 # @param StepVector vector or DirStruct or 3 vector components, defining
4111 # the direction and value of extrusion for one step (the total extrusion
4112 # length will be NbOfSteps * ||StepVector||)
4113 # @param NbOfSteps the number of steps
4114 # @param MakeGroups forces the generation of new groups from existing ones
4115 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4116 # @ingroup l2_modif_extrurev
4117 # @ref tui_extrusion example
4118 def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
4119 return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
4121 ## Generate new elements by extrusion of the elements with given ids
4122 # @param IDsOfElements is ids of elements
4123 # @param StepVector vector or DirStruct or 3 vector components, defining
4124 # the direction and value of extrusion for one step (the total extrusion
4125 # length will be NbOfSteps * ||StepVector||)
4126 # @param NbOfSteps the number of steps
4127 # @param ExtrFlags sets flags for extrusion
4128 # @param SewTolerance uses for comparing locations of nodes if flag
4129 # EXTRUSION_FLAG_SEW is set
4130 # @param MakeGroups forces the generation of new groups from existing ones
4131 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4132 # @ingroup l2_modif_extrurev
4133 def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
4134 ExtrFlags, SewTolerance, MakeGroups=False):
4135 if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
4136 StepVector = self.smeshpyD.GetDirStruct(StepVector)
4137 if isinstance( StepVector, list ):
4138 StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
4139 return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
4140 ExtrFlags, SewTolerance, MakeGroups)
4142 ## Generate new elements by extrusion of the given elements and nodes along the path.
4143 # The path of extrusion must be a meshed edge.
4144 # @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
4145 # @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
4146 # @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
4147 # @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4148 # @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
4149 # contains not only path segments, else it can be None
4150 # @param NodeStart the first or the last node on the path. Defines the direction of extrusion
4151 # @param HasAngles allows the shape to be rotated around the path
4152 # to get the resulting mesh in a helical fashion
4153 # @param Angles list of angles
4154 # @param LinearVariation forces the computation of rotation angles as linear
4155 # variation of the given Angles along path steps
4156 # @param HasRefPoint allows using the reference point
4157 # @param RefPoint the point around which the shape is rotated (the mass center of the
4158 # shape by default). The User can specify any point as the Reference Point.
4159 # @param MakeGroups forces the generation of new groups from existing ones
4160 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
4161 # @ingroup l2_modif_extrurev
4162 # @ref tui_extrusion_along_path example
4163 def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
4164 NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
4165 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
4166 unRegister = genObjUnRegister()
4167 Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
4168 Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
4169 Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
4171 if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
4172 RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
4173 if isinstance( RefPoint, list ):
4174 if not RefPoint: RefPoint = [0,0,0]
4175 RefPoint = SMESH.PointStruct( *RefPoint )
4176 if isinstance( PathMesh, Mesh ):
4177 PathMesh = PathMesh.GetMesh()
4178 Angles,AnglesParameters,hasVars = ParseAngles(Angles)
4179 Parameters = AnglesParameters + var_separator + RefPoint.parameters
4180 self.mesh.SetParameters(Parameters)
4181 return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
4182 PathMesh, PathShape, NodeStart,
4183 HasAngles, Angles, LinearVariation,
4184 HasRefPoint, RefPoint, MakeGroups)
4186 ## Generate new elements by extrusion of the given elements
4187 # The path of extrusion must be a meshed edge.
4188 # @param Base mesh or group, or sub-mesh, or list of ids of elements for extrusion
4189 # @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4190 # @param NodeStart the start node from Path. Defines the direction of extrusion
4191 # @param HasAngles allows the shape to be rotated around the path
4192 # to get the resulting mesh in a helical fashion
4193 # @param Angles list of angles in radians
4194 # @param LinearVariation forces the computation of rotation angles as linear
4195 # variation of the given Angles along path steps
4196 # @param HasRefPoint allows using the reference point
4197 # @param RefPoint the point around which the elements are rotated (the mass
4198 # center of the elements by default).
4199 # The User can specify any point as the Reference Point.
4200 # RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4201 # @param MakeGroups forces the generation of new groups from existing ones
4202 # @param ElemType type of elements for extrusion (if param Base is a mesh)
4203 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4204 # only SMESH::Extrusion_Error otherwise
4205 # @ingroup l2_modif_extrurev
4206 # @ref tui_extrusion_along_path example
4207 def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4208 HasAngles=False, Angles=[], LinearVariation=False,
4209 HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False,
4210 ElemType=SMESH.FACE):
4212 if ElemType == SMESH.NODE: n = Base
4213 if ElemType == SMESH.EDGE: e = Base
4214 if ElemType == SMESH.FACE: f = Base
4215 gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4216 HasAngles, Angles, LinearVariation,
4217 HasRefPoint, RefPoint, MakeGroups)
4218 if MakeGroups: return gr,er
4221 ## Generate new elements by extrusion of the given elements
4222 # The path of extrusion must be a meshed edge.
4223 # @param IDsOfElements ids of elements
4224 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4225 # @param PathShape shape(edge) defines the sub-mesh for the path
4226 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4227 # @param HasAngles allows the shape to be rotated around the path
4228 # to get the resulting mesh in a helical fashion
4229 # @param Angles list of angles in radians
4230 # @param HasRefPoint allows using the reference point
4231 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4232 # The User can specify any point as the Reference Point.
4233 # @param MakeGroups forces the generation of new groups from existing ones
4234 # @param LinearVariation forces the computation of rotation angles as linear
4235 # variation of the given Angles along path steps
4236 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4237 # only SMESH::Extrusion_Error otherwise
4238 # @ingroup l2_modif_extrurev
4239 # @ref tui_extrusion_along_path example
4240 def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4241 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4242 MakeGroups=False, LinearVariation=False):
4243 n,e,f = [],IDsOfElements,IDsOfElements
4244 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4245 NodeStart, HasAngles, Angles,
4247 HasRefPoint, RefPoint, MakeGroups)
4248 if MakeGroups: return gr,er
4251 ## Generate new elements by extrusion of the elements which belong to the object
4252 # The path of extrusion must be a meshed edge.
4253 # @param theObject the object whose elements should be processed.
4254 # It can be a mesh, a sub-mesh or a group.
4255 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4256 # @param PathShape shape(edge) defines the sub-mesh for the path
4257 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4258 # @param HasAngles allows the shape to be rotated around the path
4259 # to get the resulting mesh in a helical fashion
4260 # @param Angles list of angles
4261 # @param HasRefPoint allows using the reference point
4262 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4263 # The User can specify any point as the Reference Point.
4264 # @param MakeGroups forces the generation of new groups from existing ones
4265 # @param LinearVariation forces the computation of rotation angles as linear
4266 # variation of the given Angles along path steps
4267 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4268 # only SMESH::Extrusion_Error otherwise
4269 # @ingroup l2_modif_extrurev
4270 # @ref tui_extrusion_along_path example
4271 def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4272 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4273 MakeGroups=False, LinearVariation=False):
4274 n,e,f = [],theObject,theObject
4275 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4276 HasAngles, Angles, LinearVariation,
4277 HasRefPoint, RefPoint, MakeGroups)
4278 if MakeGroups: return gr,er
4281 ## Generate new elements by extrusion of mesh segments which belong to the object
4282 # The path of extrusion must be a meshed edge.
4283 # @param theObject the object whose 1D elements should be processed.
4284 # It can be a mesh, a sub-mesh or a group.
4285 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4286 # @param PathShape shape(edge) defines the sub-mesh for the path
4287 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4288 # @param HasAngles allows the shape to be rotated around the path
4289 # to get the resulting mesh in a helical fashion
4290 # @param Angles list of angles
4291 # @param HasRefPoint allows using the reference point
4292 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4293 # The User can specify any point as the Reference Point.
4294 # @param MakeGroups forces the generation of new groups from existing ones
4295 # @param LinearVariation forces the computation of rotation angles as linear
4296 # variation of the given Angles along path steps
4297 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4298 # only SMESH::Extrusion_Error otherwise
4299 # @ingroup l2_modif_extrurev
4300 # @ref tui_extrusion_along_path example
4301 def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4302 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4303 MakeGroups=False, LinearVariation=False):
4304 n,e,f = [],theObject,[]
4305 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4306 HasAngles, Angles, LinearVariation,
4307 HasRefPoint, RefPoint, MakeGroups)
4308 if MakeGroups: return gr,er
4311 ## Generate new elements by extrusion of faces which belong to the object
4312 # The path of extrusion must be a meshed edge.
4313 # @param theObject the object whose 2D elements should be processed.
4314 # It can be a mesh, a sub-mesh or a group.
4315 # @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4316 # @param PathShape shape(edge) defines the sub-mesh for the path
4317 # @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4318 # @param HasAngles allows the shape to be rotated around the path
4319 # to get the resulting mesh in a helical fashion
4320 # @param Angles list of angles
4321 # @param HasRefPoint allows using the reference point
4322 # @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4323 # The User can specify any point as the Reference Point.
4324 # @param MakeGroups forces the generation of new groups from existing ones
4325 # @param LinearVariation forces the computation of rotation angles as linear
4326 # variation of the given Angles along path steps
4327 # @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4328 # only SMESH::Extrusion_Error otherwise
4329 # @ingroup l2_modif_extrurev
4330 # @ref tui_extrusion_along_path example
4331 def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4332 HasAngles=False, Angles=[], HasRefPoint=False, RefPoint=[],
4333 MakeGroups=False, LinearVariation=False):
4334 n,e,f = [],[],theObject
4335 gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4336 HasAngles, Angles, LinearVariation,
4337 HasRefPoint, RefPoint, MakeGroups)
4338 if MakeGroups: return gr,er
4341 ## Create a symmetrical copy of mesh elements
4342 # @param IDsOfElements list of elements ids
4343 # @param Mirror is AxisStruct or geom object(point, line, plane)
4344 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4345 # If the Mirror is a geom object this parameter is unnecessary
4346 # @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4347 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4348 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4349 # @ingroup l2_modif_trsf
4350 def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4351 if IDsOfElements == []:
4352 IDsOfElements = self.GetElementsId()
4353 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4354 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4355 theMirrorType = Mirror._mirrorType
4357 self.mesh.SetParameters(Mirror.parameters)
4358 if Copy and MakeGroups:
4359 return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4360 self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4363 ## Create a new mesh by a symmetrical copy of mesh elements
4364 # @param IDsOfElements the list of elements ids
4365 # @param Mirror is AxisStruct or geom object (point, line, plane)
4366 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4367 # If the Mirror is a geom object this parameter is unnecessary
4368 # @param MakeGroups to generate new groups from existing ones
4369 # @param NewMeshName a name of the new mesh to create
4370 # @return instance of Mesh class
4371 # @ingroup l2_modif_trsf
4372 def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4373 if IDsOfElements == []:
4374 IDsOfElements = self.GetElementsId()
4375 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4376 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4377 theMirrorType = Mirror._mirrorType
4379 self.mesh.SetParameters(Mirror.parameters)
4380 mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4381 MakeGroups, NewMeshName)
4382 return Mesh(self.smeshpyD,self.geompyD,mesh)
4384 ## Create a symmetrical copy of the object
4385 # @param theObject mesh, submesh or group
4386 # @param Mirror AxisStruct or geom object (point, line, plane)
4387 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4388 # If the Mirror is a geom object this parameter is unnecessary
4389 # @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4390 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4391 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4392 # @ingroup l2_modif_trsf
4393 def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4394 if ( isinstance( theObject, Mesh )):
4395 theObject = theObject.GetMesh()
4396 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4397 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4398 theMirrorType = Mirror._mirrorType
4400 self.mesh.SetParameters(Mirror.parameters)
4401 if Copy and MakeGroups:
4402 return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4403 self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4406 ## Create a new mesh by a symmetrical copy of the object
4407 # @param theObject mesh, submesh or group
4408 # @param Mirror AxisStruct or geom object (point, line, plane)
4409 # @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4410 # If the Mirror is a geom object this parameter is unnecessary
4411 # @param MakeGroups forces the generation of new groups from existing ones
4412 # @param NewMeshName the name of the new mesh to create
4413 # @return instance of Mesh class
4414 # @ingroup l2_modif_trsf
4415 def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4416 if ( isinstance( theObject, Mesh )):
4417 theObject = theObject.GetMesh()
4418 if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4419 Mirror = self.smeshpyD.GetAxisStruct(Mirror)
4420 theMirrorType = Mirror._mirrorType
4422 self.mesh.SetParameters(Mirror.parameters)
4423 mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4424 MakeGroups, NewMeshName)
4425 return Mesh( self.smeshpyD,self.geompyD,mesh )
4427 ## Translate the elements
4428 # @param IDsOfElements list of elements ids
4429 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4430 # @param Copy allows copying the translated elements
4431 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4432 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4433 # @ingroup l2_modif_trsf
4434 def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4435 if IDsOfElements == []:
4436 IDsOfElements = self.GetElementsId()
4437 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4438 Vector = self.smeshpyD.GetDirStruct(Vector)
4439 if isinstance( Vector, list ):
4440 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4441 self.mesh.SetParameters(Vector.PS.parameters)
4442 if Copy and MakeGroups:
4443 return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4444 self.editor.Translate(IDsOfElements, Vector, Copy)
4447 ## Create a new mesh of translated elements
4448 # @param IDsOfElements list of elements ids
4449 # @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4450 # @param MakeGroups forces the generation of new groups from existing ones
4451 # @param NewMeshName the name of the newly created mesh
4452 # @return instance of Mesh class
4453 # @ingroup l2_modif_trsf
4454 def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4455 if IDsOfElements == []:
4456 IDsOfElements = self.GetElementsId()
4457 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4458 Vector = self.smeshpyD.GetDirStruct(Vector)
4459 if isinstance( Vector, list ):
4460 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4461 self.mesh.SetParameters(Vector.PS.parameters)
4462 mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4463 return Mesh ( self.smeshpyD, self.geompyD, mesh )
4465 ## Translate the object
4466 # @param theObject the object to translate (mesh, submesh, or group)
4467 # @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4468 # @param Copy allows copying the translated elements
4469 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4470 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4471 # @ingroup l2_modif_trsf
4472 def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4473 if ( isinstance( theObject, Mesh )):
4474 theObject = theObject.GetMesh()
4475 if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4476 Vector = self.smeshpyD.GetDirStruct(Vector)
4477 if isinstance( Vector, list ):
4478 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4479 self.mesh.SetParameters(Vector.PS.parameters)
4480 if Copy and MakeGroups:
4481 return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4482 self.editor.TranslateObject(theObject, Vector, Copy)
4485 ## Create a new mesh from the translated object
4486 # @param theObject the object to translate (mesh, submesh, or group)
4487 # @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4488 # @param MakeGroups forces the generation of new groups from existing ones
4489 # @param NewMeshName the name of the newly created mesh
4490 # @return instance of Mesh class
4491 # @ingroup l2_modif_trsf
4492 def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4493 if isinstance( theObject, Mesh ):
4494 theObject = theObject.GetMesh()
4495 if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4496 Vector = self.smeshpyD.GetDirStruct(Vector)
4497 if isinstance( Vector, list ):
4498 Vector = self.smeshpyD.MakeDirStruct(*Vector)
4499 self.mesh.SetParameters(Vector.PS.parameters)
4500 mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4501 return Mesh( self.smeshpyD, self.geompyD, mesh )
4506 # @param theObject - the object to translate (mesh, submesh, or group)
4507 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4508 # @param theScaleFact - list of 1-3 scale factors for axises
4509 # @param Copy - allows copying the translated elements
4510 # @param MakeGroups - forces the generation of new groups from existing
4512 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4513 # empty list otherwise
4514 def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4515 unRegister = genObjUnRegister()
4516 if ( isinstance( theObject, Mesh )):
4517 theObject = theObject.GetMesh()
4518 if ( isinstance( theObject, list )):
4519 theObject = self.GetIDSource(theObject, SMESH.ALL)
4520 unRegister.set( theObject )
4521 if ( isinstance( thePoint, list )):
4522 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4523 if ( isinstance( theScaleFact, float )):
4524 theScaleFact = [theScaleFact]
4525 if ( isinstance( theScaleFact, int )):
4526 theScaleFact = [ float(theScaleFact)]
4528 self.mesh.SetParameters(thePoint.parameters)
4530 if Copy and MakeGroups:
4531 return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4532 self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4535 ## Create a new mesh from the translated object
4536 # @param theObject - the object to translate (mesh, submesh, or group)
4537 # @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4538 # @param theScaleFact - list of 1-3 scale factors for axises
4539 # @param MakeGroups - forces the generation of new groups from existing ones
4540 # @param NewMeshName - the name of the newly created mesh
4541 # @return instance of Mesh class
4542 def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4543 unRegister = genObjUnRegister()
4544 if (isinstance(theObject, Mesh)):
4545 theObject = theObject.GetMesh()
4546 if ( isinstance( theObject, list )):
4547 theObject = self.GetIDSource(theObject,SMESH.ALL)
4548 unRegister.set( theObject )
4549 if ( isinstance( thePoint, list )):
4550 thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4551 if ( isinstance( theScaleFact, float )):
4552 theScaleFact = [theScaleFact]
4553 if ( isinstance( theScaleFact, int )):
4554 theScaleFact = [ float(theScaleFact)]
4556 self.mesh.SetParameters(thePoint.parameters)
4557 mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4558 MakeGroups, NewMeshName)
4559 return Mesh( self.smeshpyD, self.geompyD, mesh )
4563 ## Rotate the elements
4564 # @param IDsOfElements list of elements ids
4565 # @param Axis the axis of rotation (AxisStruct or geom line)
4566 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4567 # @param Copy allows copying the rotated elements
4568 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4569 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4570 # @ingroup l2_modif_trsf
4571 def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4572 if IDsOfElements == []:
4573 IDsOfElements = self.GetElementsId()
4574 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4575 Axis = self.smeshpyD.GetAxisStruct(Axis)
4576 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4577 Parameters = Axis.parameters + var_separator + Parameters
4578 self.mesh.SetParameters(Parameters)
4579 if Copy and MakeGroups:
4580 return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4581 self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4584 ## Create a new mesh of rotated elements
4585 # @param IDsOfElements list of element ids
4586 # @param Axis the axis of rotation (AxisStruct or geom line)
4587 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4588 # @param MakeGroups forces the generation of new groups from existing ones
4589 # @param NewMeshName the name of the newly created mesh
4590 # @return instance of Mesh class
4591 # @ingroup l2_modif_trsf
4592 def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4593 if IDsOfElements == []:
4594 IDsOfElements = self.GetElementsId()
4595 if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4596 Axis = self.smeshpyD.GetAxisStruct(Axis)
4597 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4598 Parameters = Axis.parameters + var_separator + Parameters
4599 self.mesh.SetParameters(Parameters)
4600 mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4601 MakeGroups, NewMeshName)
4602 return Mesh( self.smeshpyD, self.geompyD, mesh )
4604 ## Rotate the object
4605 # @param theObject the object to rotate( mesh, submesh, or group)
4606 # @param Axis the axis of rotation (AxisStruct or geom line)
4607 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4608 # @param Copy allows copying the rotated elements
4609 # @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4610 # @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4611 # @ingroup l2_modif_trsf
4612 def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4613 if (isinstance(theObject, Mesh)):
4614 theObject = theObject.GetMesh()
4615 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4616 Axis = self.smeshpyD.GetAxisStruct(Axis)
4617 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4618 Parameters = Axis.parameters + ":" + Parameters
4619 self.mesh.SetParameters(Parameters)
4620 if Copy and MakeGroups:
4621 return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4622 self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4625 ## Create a new mesh from the rotated object
4626 # @param theObject the object to rotate (mesh, submesh, or group)
4627 # @param Axis the axis of rotation (AxisStruct or geom line)
4628 # @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4629 # @param MakeGroups forces the generation of new groups from existing ones
4630 # @param NewMeshName the name of the newly created mesh
4631 # @return instance of Mesh class
4632 # @ingroup l2_modif_trsf
4633 def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4634 if (isinstance( theObject, Mesh )):
4635 theObject = theObject.GetMesh()
4636 if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4637 Axis = self.smeshpyD.GetAxisStruct(Axis)
4638 AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4639 Parameters = Axis.parameters + ":" + Parameters
4640 mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4641 MakeGroups, NewMeshName)
4642 self.mesh.SetParameters(Parameters)
4643 return Mesh( self.smeshpyD, self.geompyD, mesh )
4645 ## Find groups of adjacent nodes within Tolerance.
4646 # @param Tolerance the value of tolerance
4647 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4648 # corner and medium nodes in separate groups thus preventing
4649 # their further merge.
4650 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4651 # @ingroup l2_modif_trsf
4652 def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4653 return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4655 ## Find groups of ajacent nodes within Tolerance.
4656 # @param Tolerance the value of tolerance
4657 # @param SubMeshOrGroup SubMesh, Group or Filter
4658 # @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4659 # @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4660 # corner and medium nodes in separate groups thus preventing
4661 # their further merge.
4662 # @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4663 # @ingroup l2_modif_trsf
4664 def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4665 exceptNodes=[], SeparateCornerAndMediumNodes=False):
4666 unRegister = genObjUnRegister()
4667 if (isinstance( SubMeshOrGroup, Mesh )):
4668 SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4669 if not isinstance( exceptNodes, list ):
4670 exceptNodes = [ exceptNodes ]
4671 if exceptNodes and isinstance( exceptNodes[0], int ):
4672 exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4673 unRegister.set( exceptNodes )
4674 return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4675 exceptNodes, SeparateCornerAndMediumNodes)
4678 # @param GroupsOfNodes a list of groups of nodes IDs for merging
4679 # (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4680 # by nodes 1 and 25 correspondingly in all elements and groups
4681 # @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4682 # If @a NodesToKeep does not include a node to keep for some group to merge,
4683 # then the first node in the group is kept.
4684 # @param AvoidMakingHoles prevent merging nodes which cause removal of elements becoming
4686 # @ingroup l2_modif_trsf
4687 def MergeNodes (self, GroupsOfNodes, NodesToKeep=[], AvoidMakingHoles=False):
4688 # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4689 self.editor.MergeNodes( GroupsOfNodes, NodesToKeep, AvoidMakingHoles )
4691 ## Find the elements built on the same nodes.
4692 # @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4693 # @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4694 # @ingroup l2_modif_trsf
4695 def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4696 if not MeshOrSubMeshOrGroup:
4697 MeshOrSubMeshOrGroup=self.mesh
4698 elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4699 MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4700 return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4702 ## Merge elements in each given group.
4703 # @param GroupsOfElementsID a list of groups of elements IDs for merging
4704 # (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4705 # replaced by elements 1 and 25 in all groups)
4706 # @ingroup l2_modif_trsf
4707 def MergeElements(self, GroupsOfElementsID):
4708 self.editor.MergeElements(GroupsOfElementsID)
4710 ## Leave one element and remove all other elements built on the same nodes.
4711 # @ingroup l2_modif_trsf
4712 def MergeEqualElements(self):
4713 self.editor.MergeEqualElements()
4715 ## Return groups of FreeBorder's coincident within the given tolerance.
4716 # @param tolerance the tolerance. If the tolerance <= 0.0 then one tenth of an average
4717 # size of elements adjacent to free borders being compared is used.
4718 # @return SMESH.CoincidentFreeBorders structure
4719 # @ingroup l2_modif_trsf
4720 def FindCoincidentFreeBorders (self, tolerance=0.):
4721 return self.editor.FindCoincidentFreeBorders( tolerance )
4723 ## Sew FreeBorder's of each group
4724 # @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
4725 # where each enclosed list contains node IDs of a group of coincident free
4726 # borders such that each consequent triple of IDs within a group describes
4727 # a free border in a usual way: n1, n2, nLast - i.e. 1st node, 2nd node and
4728 # last node of a border.
4729 # For example [[1, 2, 10, 20, 21, 40], [11, 12, 15, 55, 54, 41]] describes two
4730 # groups of coincident free borders, each group including two borders.
4731 # @param createPolygons if @c True faces adjacent to free borders are converted to
4732 # polygons if a node of opposite border falls on a face edge, else such
4733 # faces are split into several ones.
4734 # @param createPolyhedra if @c True volumes adjacent to free borders are converted to
4735 # polyhedra if a node of opposite border falls on a volume edge, else such
4736 # volumes, if any, remain intact and the mesh becomes non-conformal.
4737 # @return a number of successfully sewed groups
4738 # @ingroup l2_modif_trsf
4739 def SewCoincidentFreeBorders (self, freeBorders, createPolygons=False, createPolyhedra=False):
4740 if freeBorders and isinstance( freeBorders, list ):
4741 # construct SMESH.CoincidentFreeBorders
4742 if isinstance( freeBorders[0], int ):
4743 freeBorders = [freeBorders]
4745 coincidentGroups = []
4746 for nodeList in freeBorders:
4747 if not nodeList or len( nodeList ) % 3:
4748 raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
4751 group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
4752 borders.append( SMESH.FreeBorder( nodeList[:3] ))
4753 nodeList = nodeList[3:]
4755 coincidentGroups.append( group )
4757 freeBorders = SMESH.CoincidentFreeBorders( borders, coincidentGroups )
4759 return self.editor.SewCoincidentFreeBorders( freeBorders, createPolygons, createPolyhedra )
4762 # @return SMESH::Sew_Error
4763 # @ingroup l2_modif_trsf
4764 def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4765 FirstNodeID2, SecondNodeID2, LastNodeID2,
4766 CreatePolygons, CreatePolyedrs):
4767 return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4768 FirstNodeID2, SecondNodeID2, LastNodeID2,
4769 CreatePolygons, CreatePolyedrs)
4771 ## Sew conform free borders
4772 # @return SMESH::Sew_Error
4773 # @ingroup l2_modif_trsf
4774 def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4775 FirstNodeID2, SecondNodeID2):
4776 return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4777 FirstNodeID2, SecondNodeID2)
4779 ## Sew border to side
4780 # @return SMESH::Sew_Error
4781 # @ingroup l2_modif_trsf
4782 def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4783 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4784 return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4785 FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4787 ## Sew two sides of a mesh. The nodes belonging to Side1 are
4788 # merged with the nodes of elements of Side2.
4789 # The number of elements in theSide1 and in theSide2 must be
4790 # equal and they should have similar nodal connectivity.
4791 # The nodes to merge should belong to side borders and
4792 # the first node should be linked to the second.
4793 # @return SMESH::Sew_Error
4794 # @ingroup l2_modif_trsf
4795 def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4796 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4797 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4798 return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4799 NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4800 NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4802 ## Set new nodes for the given element.
4803 # @param ide the element id
4804 # @param newIDs nodes ids
4805 # @return If the number of nodes does not correspond to the type of element - return false
4806 # @ingroup l2_modif_edit
4807 def ChangeElemNodes(self, ide, newIDs):
4808 return self.editor.ChangeElemNodes(ide, newIDs)
4810 ## If during the last operation of MeshEditor some nodes were
4811 # created, this method return the list of their IDs, \n
4812 # if new nodes were not created - return empty list
4813 # @return the list of integer values (can be empty)
4814 # @ingroup l2_modif_add
4815 def GetLastCreatedNodes(self):
4816 return self.editor.GetLastCreatedNodes()
4818 ## If during the last operation of MeshEditor some elements were
4819 # created this method return the list of their IDs, \n
4820 # if new elements were not created - return empty list
4821 # @return the list of integer values (can be empty)
4822 # @ingroup l2_modif_add
4823 def GetLastCreatedElems(self):
4824 return self.editor.GetLastCreatedElems()
4826 ## Forget what nodes and elements were created by the last mesh edition operation
4827 # @ingroup l2_modif_add
4828 def ClearLastCreated(self):
4829 self.editor.ClearLastCreated()
4831 ## Create duplicates of given elements, i.e. create new elements based on the
4832 # same nodes as the given ones.
4833 # @param theElements - container of elements to duplicate. It can be a Mesh,
4834 # sub-mesh, group, filter or a list of element IDs. If \a theElements is
4835 # a Mesh, elements of highest dimension are duplicated
4836 # @param theGroupName - a name of group to contain the generated elements.
4837 # If a group with such a name already exists, the new elements
4838 # are added to the existng group, else a new group is created.
4839 # If \a theGroupName is empty, new elements are not added
4841 # @return a group where the new elements are added. None if theGroupName == "".
4842 # @ingroup l2_modif_duplicat
4843 def DoubleElements(self, theElements, theGroupName=""):
4844 unRegister = genObjUnRegister()
4845 if isinstance( theElements, Mesh ):
4846 theElements = theElements.mesh
4847 elif isinstance( theElements, list ):
4848 theElements = self.GetIDSource( theElements, SMESH.ALL )
4849 unRegister.set( theElements )
4850 return self.editor.DoubleElements(theElements, theGroupName)
4852 ## Create a hole in a mesh by doubling the nodes of some particular elements
4853 # @param theNodes identifiers of nodes to be doubled
4854 # @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4855 # nodes. If list of element identifiers is empty then nodes are doubled but
4856 # they not assigned to elements
4857 # @return TRUE if operation has been completed successfully, FALSE otherwise
4858 # @ingroup l2_modif_duplicat
4859 def DoubleNodes(self, theNodes, theModifiedElems):
4860 return self.editor.DoubleNodes(theNodes, theModifiedElems)
4862 ## Create a hole in a mesh by doubling the nodes of some particular elements
4863 # This method provided for convenience works as DoubleNodes() described above.
4864 # @param theNodeId identifiers of node to be doubled
4865 # @param theModifiedElems identifiers of elements to be updated
4866 # @return TRUE if operation has been completed successfully, FALSE otherwise
4867 # @ingroup l2_modif_duplicat
4868 def DoubleNode(self, theNodeId, theModifiedElems):
4869 return self.editor.DoubleNode(theNodeId, theModifiedElems)
4871 ## Create a hole in a mesh by doubling the nodes of some particular elements
4872 # This method provided for convenience works as DoubleNodes() described above.
4873 # @param theNodes group of nodes to be doubled
4874 # @param theModifiedElems group of elements to be updated.
4875 # @param theMakeGroup forces the generation of a group containing new nodes.
4876 # @return TRUE or a created group if operation has been completed successfully,
4877 # FALSE or None otherwise
4878 # @ingroup l2_modif_duplicat
4879 def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4881 return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4882 return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4884 ## Create a hole in a mesh by doubling the nodes of some particular elements
4885 # This method provided for convenience works as DoubleNodes() described above.
4886 # @param theNodes list of groups of nodes to be doubled
4887 # @param theModifiedElems list of groups of elements to be updated.
4888 # @param theMakeGroup forces the generation of a group containing new nodes.
4889 # @return TRUE if operation has been completed successfully, FALSE otherwise
4890 # @ingroup l2_modif_duplicat
4891 def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4893 return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4894 return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4896 ## Create a hole in a mesh by doubling the nodes of some particular elements
4897 # @param theElems - the list of elements (edges or faces) to be replicated
4898 # The nodes for duplication could be found from these elements
4899 # @param theNodesNot - list of nodes to NOT replicate
4900 # @param theAffectedElems - the list of elements (cells and edges) to which the
4901 # replicated nodes should be associated to.
4902 # @return TRUE if operation has been completed successfully, FALSE otherwise
4903 # @ingroup l2_modif_duplicat
4904 def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4905 return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4907 ## Create a hole in a mesh by doubling the nodes of some particular elements
4908 # @param theElems - the list of elements (edges or faces) to be replicated
4909 # The nodes for duplication could be found from these elements
4910 # @param theNodesNot - list of nodes to NOT replicate
4911 # @param theShape - shape to detect affected elements (element which geometric center
4912 # located on or inside shape).
4913 # The replicated nodes should be associated to affected elements.
4914 # @return TRUE if operation has been completed successfully, FALSE otherwise
4915 # @ingroup l2_modif_duplicat
4916 def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4917 return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4919 ## Create a hole in a mesh by doubling the nodes of some particular elements
4920 # This method provided for convenience works as DoubleNodes() described above.
4921 # @param theElems - group of of elements (edges or faces) to be replicated
4922 # @param theNodesNot - group of nodes not to replicated
4923 # @param theAffectedElems - group of elements to which the replicated nodes
4924 # should be associated to.
4925 # @param theMakeGroup forces the generation of a group containing new elements.
4926 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4927 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4928 # FALSE or None otherwise
4929 # @ingroup l2_modif_duplicat
4930 def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4931 theMakeGroup=False, theMakeNodeGroup=False):
4932 if theMakeGroup or theMakeNodeGroup:
4933 twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4935 theMakeGroup, theMakeNodeGroup)
4936 if theMakeGroup and theMakeNodeGroup:
4939 return twoGroups[ int(theMakeNodeGroup) ]
4940 return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4942 ## Create a hole in a mesh by doubling the nodes of some particular elements
4943 # This method provided for convenience works as DoubleNodes() described above.
4944 # @param theElems - group of of elements (edges or faces) to be replicated
4945 # @param theNodesNot - group of nodes not to replicated
4946 # @param theShape - shape to detect affected elements (element which geometric center
4947 # located on or inside shape).
4948 # The replicated nodes should be associated to affected elements.
4949 # @ingroup l2_modif_duplicat
4950 def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4951 return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4953 ## Create a hole in a mesh by doubling the nodes of some particular elements
4954 # This method provided for convenience works as DoubleNodes() described above.
4955 # @param theElems - list of groups of elements (edges or faces) to be replicated
4956 # @param theNodesNot - list of groups of nodes not to replicated
4957 # @param theAffectedElems - group of elements to which the replicated nodes
4958 # should be associated to.
4959 # @param theMakeGroup forces the generation of a group containing new elements.
4960 # @param theMakeNodeGroup forces the generation of a group containing new nodes.
4961 # @return TRUE or created groups (one or two) if operation has been completed successfully,
4962 # FALSE or None otherwise
4963 # @ingroup l2_modif_duplicat
4964 def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4965 theMakeGroup=False, theMakeNodeGroup=False):
4966 if theMakeGroup or theMakeNodeGroup:
4967 twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4969 theMakeGroup, theMakeNodeGroup)
4970 if theMakeGroup and theMakeNodeGroup:
4973 return twoGroups[ int(theMakeNodeGroup) ]
4974 return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4976 ## Create a hole in a mesh by doubling the nodes of some particular elements
4977 # This method provided for convenience works as DoubleNodes() described above.
4978 # @param theElems - list of groups of elements (edges or faces) to be replicated
4979 # @param theNodesNot - list of groups of nodes not to replicated
4980 # @param theShape - shape to detect affected elements (element which geometric center
4981 # located on or inside shape).
4982 # The replicated nodes should be associated to affected elements.
4983 # @return TRUE if operation has been completed successfully, FALSE otherwise
4984 # @ingroup l2_modif_duplicat
4985 def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4986 return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4988 ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4989 # This method is the first step of DoubleNodeElemGroupsInRegion.
4990 # @param theElems - list of groups of elements (edges or faces) to be replicated
4991 # @param theNodesNot - list of groups of nodes not to replicated
4992 # @param theShape - shape to detect affected elements (element which geometric center
4993 # located on or inside shape).
4994 # The replicated nodes should be associated to affected elements.
4995 # @return groups of affected elements
4996 # @ingroup l2_modif_duplicat
4997 def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4998 return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
5000 ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
5001 # The list of groups must describe a partition of the mesh volumes.
5002 # The nodes of the internal faces at the boundaries of the groups are doubled.
5003 # In option, the internal faces are replaced by flat elements.
5004 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5005 # @param theDomains - list of groups of volumes
5006 # @param createJointElems - if TRUE, create the elements
5007 # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
5008 # the boundary between \a theDomains and the rest mesh
5009 # @return TRUE if operation has been completed successfully, FALSE otherwise
5010 # @ingroup l2_modif_duplicat
5011 def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
5012 return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
5014 ## Double nodes on some external faces and create flat elements.
5015 # Flat elements are mainly used by some types of mechanic calculations.
5017 # Each group of the list must be constituted of faces.
5018 # Triangles are transformed in prisms, and quadrangles in hexahedrons.
5019 # @param theGroupsOfFaces - list of groups of faces
5020 # @return TRUE if operation has been completed successfully, FALSE otherwise
5021 # @ingroup l2_modif_duplicat
5022 def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
5023 return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
5025 ## identify all the elements around a geom shape, get the faces delimiting the hole
5027 def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
5028 return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
5030 def _getFunctor(self, funcType ):
5031 fn = self.functors[ EnumToLong(funcType) ]
5033 fn = self.smeshpyD.GetFunctor(funcType)
5034 fn.SetMesh(self.mesh)
5035 self.functors[ EnumToLong(funcType) ] = fn
5038 ## Return value of a functor for a given element
5039 # @param funcType an item of SMESH.FunctorType enum
5040 # Type "SMESH.FunctorType._items" in the Python Console to see all items.
5041 # @param elemId element or node ID
5042 # @param isElem @a elemId is ID of element or node
5043 # @return the functor value or zero in case of invalid arguments
5044 # @ingroup l1_measurements
5045 def FunctorValue(self, funcType, elemId, isElem=True):
5046 fn = self._getFunctor( funcType )
5047 if fn.GetElementType() == self.GetElementType(elemId, isElem):
5048 val = fn.GetValue(elemId)
5053 ## Get length of 1D element or sum of lengths of all 1D mesh elements
5054 # @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
5055 # @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
5056 # @ingroup l1_measurements
5057 def GetLength(self, elemId=None):
5060 length = self.smeshpyD.GetLength(self)
5062 length = self.FunctorValue(SMESH.FT_Length, elemId)
5065 ## Get area of 2D element or sum of areas of all 2D mesh elements
5066 # @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
5067 # @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
5068 # @ingroup l1_measurements
5069 def GetArea(self, elemId=None):
5072 area = self.smeshpyD.GetArea(self)
5074 area = self.FunctorValue(SMESH.FT_Area, elemId)
5077 ## Get volume of 3D element or sum of volumes of all 3D mesh elements
5078 # @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
5079 # @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
5080 # @ingroup l1_measurements
5081 def GetVolume(self, elemId=None):
5084 volume = self.smeshpyD.GetVolume(self)
5086 volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
5089 ## Get maximum element length.
5090 # @param elemId mesh element ID
5091 # @return element's maximum length value
5092 # @ingroup l1_measurements
5093 def GetMaxElementLength(self, elemId):
5094 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5095 ftype = SMESH.FT_MaxElementLength3D
5097 ftype = SMESH.FT_MaxElementLength2D
5098 return self.FunctorValue(ftype, elemId)
5100 ## Get aspect ratio of 2D or 3D element.
5101 # @param elemId mesh element ID
5102 # @return element's aspect ratio value
5103 # @ingroup l1_measurements
5104 def GetAspectRatio(self, elemId):
5105 if self.GetElementType(elemId, True) == SMESH.VOLUME:
5106 ftype = SMESH.FT_AspectRatio3D
5108 ftype = SMESH.FT_AspectRatio
5109 return self.FunctorValue(ftype, elemId)
5111 ## Get warping angle of 2D element.
5112 # @param elemId mesh element ID
5113 # @return element's warping angle value
5114 # @ingroup l1_measurements
5115 def GetWarping(self, elemId):
5116 return self.FunctorValue(SMESH.FT_Warping, elemId)
5118 ## Get minimum angle of 2D element.
5119 # @param elemId mesh element ID
5120 # @return element's minimum angle value
5121 # @ingroup l1_measurements
5122 def GetMinimumAngle(self, elemId):
5123 return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
5125 ## Get taper of 2D element.
5126 # @param elemId mesh element ID
5127 # @return element's taper value
5128 # @ingroup l1_measurements
5129 def GetTaper(self, elemId):
5130 return self.FunctorValue(SMESH.FT_Taper, elemId)
5132 ## Get skew of 2D element.
5133 # @param elemId mesh element ID
5134 # @return element's skew value
5135 # @ingroup l1_measurements
5136 def GetSkew(self, elemId):
5137 return self.FunctorValue(SMESH.FT_Skew, elemId)
5139 ## Return minimal and maximal value of a given functor.
5140 # @param funType a functor type, an item of SMESH.FunctorType enum
5141 # (one of SMESH.FunctorType._items)
5142 # @param meshPart a part of mesh (group, sub-mesh) to treat
5143 # @return tuple (min,max)
5144 # @ingroup l1_measurements
5145 def GetMinMax(self, funType, meshPart=None):
5146 unRegister = genObjUnRegister()
5147 if isinstance( meshPart, list ):
5148 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
5149 unRegister.set( meshPart )
5150 if isinstance( meshPart, Mesh ):
5151 meshPart = meshPart.mesh
5152 fun = self._getFunctor( funType )
5155 if hasattr( meshPart, "SetMesh" ):
5156 meshPart.SetMesh( self.mesh ) # set mesh to filter
5157 hist = fun.GetLocalHistogram( 1, False, meshPart )
5159 hist = fun.GetHistogram( 1, False )
5161 return hist[0].min, hist[0].max
5164 pass # end of Mesh class
5167 ## Private class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
5168 # with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
5170 class meshProxy(SMESH._objref_SMESH_Mesh):
5171 def __init__(self, *args):
5172 SMESH._objref_SMESH_Mesh.__init__(self, *args)
5173 def __deepcopy__(self, memo=None):
5174 new = self.__class__(self)
5176 def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
5177 if len( args ) == 3:
5178 args += SMESH.ALL_NODES, True
5179 return SMESH._objref_SMESH_Mesh.CreateDimGroup(self, *args)
5180 def ExportToMEDX(self, *args): # function removed
5181 print("WARNING: ExportToMEDX() is deprecated, use ExportMED() instead")
5182 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5183 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5184 def ExportToMED(self, *args): # function removed
5185 print("WARNING: ExportToMED() is deprecated, use ExportMED() instead")
5186 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5187 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5189 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5190 def ExportPartToMED(self, *args): # 'version' parameter removed
5191 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5192 SMESH._objref_SMESH_Mesh.ExportPartToMED(self, *args)
5193 def ExportMED(self, *args): # signature of method changed
5194 args = [i for i in args if i not in [SMESH.MED_V2_1, SMESH.MED_V2_2]]
5195 while len(args) < 4: # !!!! nb of parameters for ExportToMED IDL's method
5197 SMESH._objref_SMESH_Mesh.ExportMED(self, *args)
5199 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
5202 ## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
5204 class submeshProxy(SMESH._objref_SMESH_subMesh):
5205 def __init__(self, *args):
5206 SMESH._objref_SMESH_subMesh.__init__(self, *args)
5208 def __deepcopy__(self, memo=None):
5209 new = self.__class__(self)
5212 ## Compute the sub-mesh and return the status of the computation
5213 # @param refresh if @c True, Object browser is automatically updated (when running in GUI)
5214 # @return True or False
5216 # This is a method of SMESH.SMESH_submesh that can be obtained via Mesh.GetSubMesh() or
5217 # @ref smesh_algorithm.Mesh_Algorithm.GetSubMesh() "Mesh_Algorithm.GetSubMesh()".
5218 # @ingroup l2_submeshes
5219 def Compute(self,refresh=False):
5221 self.mesh = Mesh( smeshBuilder(), None, self.GetMesh())
5223 ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
5225 if salome.sg.hasDesktop():
5226 smeshgui = salome.ImportComponentGUI("SMESH")
5228 smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
5229 if refresh: salome.sg.updateObjBrowser()
5234 omniORB.registerObjref(SMESH._objref_SMESH_subMesh._NP_RepositoryId, submeshProxy)
5237 ## Private class used to compensate change of CORBA API of SMESH_MeshEditor for backward
5238 # compatibility with old dump scripts which call SMESH_MeshEditor directly and not via
5241 class meshEditor(SMESH._objref_SMESH_MeshEditor):
5242 def __init__(self, *args):
5243 SMESH._objref_SMESH_MeshEditor.__init__(self, *args)
5245 def __getattr__(self, name ): # method called if an attribute not found
5246 if not self.mesh: # look for name() method in Mesh class
5247 self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
5248 if hasattr( self.mesh, name ):
5249 return getattr( self.mesh, name )
5250 if name == "ExtrusionAlongPathObjX":
5251 return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
5252 print("meshEditor: attribute '%s' NOT FOUND" % name)
5254 def __deepcopy__(self, memo=None):
5255 new = self.__class__(self)
5257 def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
5258 if len( args ) == 1: args += False,
5259 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
5260 def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
5261 if len( args ) == 2: args += False,
5262 return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
5263 def MergeNodes(self,*args): # 2 args added (NodesToKeep,AvoidMakingHoles)
5264 if len( args ) == 1:
5265 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [], False )
5266 NodesToKeep = args[1]
5267 AvoidMakingHoles = args[2] if len( args ) == 3 else False
5268 unRegister = genObjUnRegister()
5270 if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
5271 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
5272 if not isinstance( NodesToKeep, list ):
5273 NodesToKeep = [ NodesToKeep ]
5274 return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep, AvoidMakingHoles )
5276 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
5278 ## Private class wrapping SMESH.SMESH_Pattern CORBA class in order to treat Notebook
5279 # variables in some methods
5281 class Pattern(SMESH._objref_SMESH_Pattern):
5283 def LoadFromFile(self, patternTextOrFile ):
5284 text = patternTextOrFile
5285 if os.path.exists( text ):
5286 text = open( patternTextOrFile ).read()
5288 return SMESH._objref_SMESH_Pattern.LoadFromFile( self, text )
5290 def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
5291 decrFun = lambda i: i-1
5292 theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
5293 theMesh.SetParameters(Parameters)
5294 return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
5296 def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
5297 decrFun = lambda i: i-1
5298 theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
5299 theMesh.SetParameters(Parameters)
5300 return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
5302 def MakeMesh(self, mesh, CreatePolygons=False, CreatePolyhedra=False):
5303 if isinstance( mesh, Mesh ):
5304 mesh = mesh.GetMesh()
5305 return SMESH._objref_SMESH_Pattern.MakeMesh( self, mesh, CreatePolygons, CreatePolyhedra )
5307 # Registering the new proxy for Pattern
5308 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
5310 ## Private class used to bind methods creating algorithms to the class Mesh
5313 def __init__(self, method):
5315 self.defaultAlgoType = ""
5316 self.algoTypeToClass = {}
5317 self.method = method
5319 # Store a python class of algorithm
5320 def add(self, algoClass):
5321 if inspect.isclass(algoClass) and \
5322 hasattr(algoClass, "algoType"):
5323 self.algoTypeToClass[ algoClass.algoType ] = algoClass
5324 if not self.defaultAlgoType and \
5325 hasattr( algoClass, "isDefault") and algoClass.isDefault:
5326 self.defaultAlgoType = algoClass.algoType
5327 #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5329 # Create a copy of self and assign mesh to the copy
5330 def copy(self, mesh):
5331 other = algoCreator( self.method )
5332 other.defaultAlgoType = self.defaultAlgoType
5333 other.algoTypeToClass = self.algoTypeToClass
5337 # Create an instance of algorithm
5338 def __call__(self,algo="",geom=0,*args):
5341 if isinstance( algo, str ):
5343 elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
5344 not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
5349 if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
5351 elif not algoType and isinstance( geom, str ):
5356 if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
5358 elif isinstance( arg, str ) and not algoType:
5361 import traceback, sys
5362 msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
5363 sys.stderr.write( msg + '\n' )
5364 tb = traceback.extract_stack(None,2)
5365 traceback.print_list( [tb[0]] )
5367 algoType = self.defaultAlgoType
5368 if not algoType and self.algoTypeToClass:
5369 algoType = list(self.algoTypeToClass.keys())[0]
5370 if algoType in self.algoTypeToClass:
5371 #print "Create algo",algoType
5373 return self.algoTypeToClass[ algoType ]( self.mesh, shape )
5374 raise RuntimeError( "No class found for algo type %s" % algoType)
5377 ## Private class used to substitute and store variable parameters of hypotheses.
5379 class hypMethodWrapper:
5380 def __init__(self, hyp, method):
5382 self.method = method
5383 #print "REBIND:", method.__name__
5386 # call a method of hypothesis with calling SetVarParameter() before
5387 def __call__(self,*args):
5389 return self.method( self.hyp, *args ) # hypothesis method with no args
5391 #print "MethWrapper.__call__",self.method.__name__, args
5393 parsed = ParseParameters(*args) # replace variables with their values
5394 self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5395 result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5396 except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5397 # maybe there is a replaced string arg which is not variable
5398 result = self.method( self.hyp, *args )
5399 except ValueError as detail: # raised by ParseParameters()
5401 result = self.method( self.hyp, *args )
5402 except omniORB.CORBA.BAD_PARAM:
5403 raise ValueError(detail) # wrong variable name
5408 ## A helper class that calls UnRegister() of SALOME.GenericObj'es stored in it
5410 class genObjUnRegister:
5412 def __init__(self, genObj=None):
5413 self.genObjList = []
5417 def set(self, genObj):
5418 "Store one or a list of of SALOME.GenericObj'es"
5419 if isinstance( genObj, list ):
5420 self.genObjList.extend( genObj )
5422 self.genObjList.append( genObj )
5426 for genObj in self.genObjList:
5427 if genObj and hasattr( genObj, "UnRegister" ):
5431 ## Bind methods creating mesher plug-ins to the Mesh class
5433 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5435 #print "pluginName: ", pluginName
5436 pluginBuilderName = pluginName + "Builder"
5438 exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5439 except Exception as e:
5440 from salome_utils import verbose
5441 if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
5443 exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5444 plugin = eval( pluginBuilderName )
5445 #print " plugin:" , str(plugin)
5447 # add methods creating algorithms to Mesh
5448 for k in dir( plugin ):
5449 if k[0] == '_': continue
5450 algo = getattr( plugin, k )
5451 #print " algo:", str(algo)
5452 if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
5453 #print " meshMethod:" , str(algo.meshMethod)
5454 if not hasattr( Mesh, algo.meshMethod ):
5455 setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
5457 getattr( Mesh, algo.meshMethod ).add( algo )