salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
cartAlgo = mesh.BodyFitted()
# define a cartesian grid using Coordinates
- coords = range(-100,100,10)
+ coords = list(range(-100,100,10))
cartHyp = cartAlgo.SetGrid( coords,coords,coords, 1000000)
# compute the mesh
mesh.Compute()
- print "nb hexahedra",mesh.NbHexas()
- print "nb tetrahedra",mesh.NbTetras()
- print "nb polyhedra",mesh.NbPolyhedrons()
- print
+ print("nb hexahedra",mesh.NbHexas())
+ print("nb tetrahedra",mesh.NbTetras())
+ print("nb polyhedra",mesh.NbPolyhedrons())
+ print()
# define the grid by setting constant spacing
cartHyp = cartAlgo.SetGrid( "10","10","10", 1000000)
mesh.Compute()
- print "nb hexahedra",mesh.NbHexas()
- print "nb tetrahedra",mesh.NbTetras()
- print "nb polyhedra",mesh.NbPolyhedrons()
+ print("nb hexahedra",mesh.NbHexas())
+ print("nb tetrahedra",mesh.NbTetras())
+ print("nb polyhedra",mesh.NbPolyhedrons())
# define the grid by setting different spacing in 2 sub-ranges of geometry
cartAlgo.SetGrid( [spaceFuns, [0.5]], [spaceFuns, [0.5]], [spaceFuns, [0.25]], 10 )
mesh.Compute()
- print "nb hexahedra",mesh.NbHexas()
- print "nb tetrahedra",mesh.NbTetras()
- print "nb polyhedra",mesh.NbPolyhedrons()
- print
+ print("nb hexahedra",mesh.NbHexas())
+ print("nb tetrahedra",mesh.NbTetras())
+ print("nb polyhedra",mesh.NbPolyhedrons())
+ print()
# Example of customization of dirtections of the grid axes
algo = mesh.BodyFitted()
algo.SetGrid( spc, spc, spc, 10000 )
mesh.Compute()
- print "Default axes"
- print " nb hex:",mesh.NbHexas()
+ print("Default axes")
+ print(" nb hex:",mesh.NbHexas())
# set axes using edges of the box
algo.SetAxesDirs( xDir, [-0.1,1,0], zDir )
mesh.Compute()
- print "Manual axes"
- print " nb hex:",mesh.NbHexas()
+ print("Manual axes")
+ print(" nb hex:",mesh.NbHexas())
# set optimal orthogonal axes
algo.SetOptimalAxesDirs( isOrthogonal=True )
mesh.Compute()
- print "Optimal orthogonal axes"
- print " nb hex:",mesh.NbHexas()
+ print("Optimal orthogonal axes")
+ print(" nb hex:",mesh.NbHexas())
# set optimal non-orthogonal axes
algo.SetOptimalAxesDirs( isOrthogonal=False )
mesh.Compute()
- print "Optimal non-orthogonal axes"
- print " nb hex:",mesh.NbHexas()
+ print("Optimal non-orthogonal axes")
+ print(" nb hex:",mesh.NbHexas())
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a box
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
# compute the mesh
ret = tetra.Compute()
if ret == 0:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
else:
- print "mesh computed"
+ print("mesh computed")
pass
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
Box_1 = geompy.MakeBoxDXDYDZ(200, 200, 200)
[Face_1,Face_2,Face_3,Face_4,Face_5,Face_6] = geompy.SubShapeAllSorted(Box_1, geompy.ShapeType["FACE"])
# check exisiting sub-mesh priority order
[ [ SubMesh_1, SubMesh_3, SubMesh_2 ] ] = Mesh_1.GetMeshOrder()
isDone = Mesh_1.Compute()
- print "Nb elements at initial order of sub-meshes:", Mesh_1.NbElements()
+ print("Nb elements at initial order of sub-meshes:", Mesh_1.NbElements())
# set new sub-mesh order
isDone = Mesh_1.SetMeshOrder( [ [ SubMesh_1, SubMesh_2, SubMesh_3 ] ])
# compute mesh
isDone = Mesh_1.Compute()
- print "Nb elements at new order of sub-meshes:", Mesh_1.NbElements()
+ print("Nb elements at new order of sub-meshes:", Mesh_1.NbElements())
# compute with other sub-mesh order
isDone = Mesh_1.SetMeshOrder( [ [ SubMesh_2, SubMesh_1, SubMesh_3 ] ])
isDone = Mesh_1.Compute()
- print "Nb elements at another order of sub-meshes:", Mesh_1.NbElements()
+ print("Nb elements at another order of sub-meshes:", Mesh_1.NbElements())
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
def PrintMeshInfo(theMesh):
aMesh = theMesh.GetMesh()
- print "Information about mesh:"
- print "Number of nodes : ", aMesh.NbNodes()
- print "Number of edges : ", aMesh.NbEdges()
- print "Number of faces : ", aMesh.NbFaces()
- print "Number of volumes : ", aMesh.NbVolumes()
+ print("Information about mesh:")
+ print("Number of nodes : ", aMesh.NbNodes())
+ print("Number of edges : ", aMesh.NbEdges())
+ print("Number of faces : ", aMesh.NbFaces())
+ print("Number of volumes : ", aMesh.NbVolumes())
pass
# create a box
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a box
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
# on XOY plane, and autoDimension=True by default
mesh2D.ExportMED( medFile )
medMesh = MEDLoader.MEDLoader.ReadUMeshFromFile(medFile,mesh2D.GetName(),0)
- print "autoDimension==True, exported mesh is in %sD"%medMesh.getSpaceDimension()
+ print("autoDimension==True, exported mesh is in %sD"%medMesh.getSpaceDimension())
# exported mesh is in 3D space, same as in Mesh module,
# thanks to autoDimension=False
mesh2D.ExportMED( medFile, autoDimension=False )
medMesh = MEDLoader.MEDLoader.ReadUMeshFromFile(medFile,mesh2D.GetName(),0)
- print "autoDimension==False, exported mesh is in %sD"%medMesh.getSpaceDimension()
+ print("autoDimension==False, exported mesh is in %sD"%medMesh.getSpaceDimension())
os.remove( medFile )
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a cylinder
cyl = geompy.MakeCylinderRH(30., 50.)
# compute the mesh
ret = tetra.Compute()
if ret == 0:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
else:
- print "Computation succeeded"
+ print("Computation succeeded")
import salome, SMESH
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create mesh
face = geompy.MakeFaceHW(100, 100, 1, theName="quadrangle")
# get all free borders
filter = smesh.GetFilter(SMESH.EDGE, SMESH.FT_FreeBorders)
ids = mesh.GetIdsFromFilter(filter)
- print "Number of edges on free borders:", len(ids)
+ print("Number of edges on free borders:", len(ids))
import salome, SMESH
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create mesh
face = geompy.MakeFaceHW(100, 100, 1)
# get all faces with free edges
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_FreeEdges)
ids = mesh.GetIdsFromFilter(filter)
- print "Number of faces with free edges:", len(ids)
+ print("Number of faces with free edges:", len(ids))
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
# make a mesh on a box
equalFacesFilter = smesh.GetFilter(SMESH.FACE, SMESH.FT_EqualFaces)
equalVolumesFilter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_EqualVolumes)
# get equal elements
- print "Number of equal edges:", len( mesh.GetIdsFromFilter( equalEdgesFilter ))
- print "Number of equal faces:", len( mesh.GetIdsFromFilter( equalFacesFilter ))
- print "Number of equal volumes:", len( mesh.GetIdsFromFilter( equalVolumesFilter ))
+ print("Number of equal edges:", len( mesh.GetIdsFromFilter( equalEdgesFilter )))
+ print("Number of equal faces:", len( mesh.GetIdsFromFilter( equalFacesFilter )))
+ print("Number of equal volumes:", len( mesh.GetIdsFromFilter( equalVolumesFilter )))
import salome
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# make a mesh on a box
box = geompy.MakeBoxDXDYDZ(100,100,100)
# create a filter to find nodes equal within tolerance of 1e-5
filter = smesh.GetFilter(SMESH.NODE, SMESH.FT_EqualNodes, Tolerance=1e-5)
# get equal nodes
- print "Number of equal nodes:", len( mesh.GetIdsFromFilter( filter ))
+ print("Number of equal nodes:", len( mesh.GetIdsFromFilter( filter )))
import salome
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# make a mesh on a box
box = geompy.MakeBoxDXDYDZ(100,100,100)
# get mesh edges with number of connected elements (faces and volumes) == 3
filter = smesh.GetFilter(SMESH.EDGE, SMESH.FT_MultiConnection, 3)
ids = mesh.GetIdsFromFilter(filter)
- print "Number of border edges with 3 faces connected:", len(ids)
+ print("Number of border edges with 3 faces connected:", len(ids))
import salome, SMESH
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create two boxes to have two domains in the mesh
# using point coordinates in box_1
nodeFilter = smesh.GetFilter( SMESH.NODE, SMESH.FT_ConnectedElements, "=", "1.,2,10", mesh=mesh )
- print "Nb. nodes in box_1:", len( nodeFilter.GetIDs())
+ print("Nb. nodes in box_1:", len( nodeFilter.GetIDs()))
# using point coordinates in box_2
edgeFilter = smesh.GetFilter( SMESH.EDGE, SMESH.FT_ConnectedElements, "=", [202,1,1 ], mesh=mesh )
- print "Nb. segments in box_2:", len( edgeFilter.GetIDs())
+ print("Nb. segments in box_2:", len( edgeFilter.GetIDs()))
# using a geom vertex of box_1
faceFilter = smesh.GetFilter( SMESH.FACE, SMESH.FT_ConnectedElements, "=", vertex, mesh=mesh )
- print "Nb. faces in box_1:", len( edgeFilter.GetIDs())
+ print("Nb. faces in box_1:", len( edgeFilter.GetIDs()))
# using node ID in box_2
voluFilter = smesh.GetFilter( SMESH.VOLUME, SMESH.FT_ConnectedElements, "=", 10, mesh=mesh )
- print "Nb. volumes in box_2:", len( voluFilter.GetIDs())
+ print("Nb. volumes in box_2:", len( voluFilter.GetIDs()))
# set/get group name
aGroup.SetName( "new name" )
- print "name", aGroup.GetName()
+ print("name", aGroup.GetName())
# get group type (type of entities in the group, SMESH.NODE in our case)
- print "type", aGroup.GetType()
+ print("type", aGroup.GetType())
# get number of entities (nodes in our case) in the group
- print "size", aGroup.Size()
+ print("size", aGroup.Size())
# check of emptiness
- print "is empty", aGroup.IsEmpty()
+ print("is empty", aGroup.IsEmpty())
# check of presence of an entity in the group
aGroup.Add([1,2]) # Add() method is specific to the standalone group
- print "contains node 2", aGroup.Contains(2)
+ print("contains node 2", aGroup.Contains(2))
# get an entity by index
- print "1st node", aGroup.GetID(1)
+ print("1st node", aGroup.GetID(1))
# get all entities
- print "all", aGroup.GetIDs()
+ print("all", aGroup.GetIDs())
# get number of nodes (actual for groups of elements)
- print "nb nodes", aGroup.GetNumberOfNodes()
+ print("nb nodes", aGroup.GetNumberOfNodes())
# get underlying nodes (actual for groups of elements)
- print "nodes", aGroup.GetNodeIDs()
+ print("nodes", aGroup.GetNodeIDs())
# set/get color
import SALOMEDS
aGroup.SetColor( SALOMEDS.Color(1.,1.,0.));
- print "color", aGroup.GetColor()
+ print("color", aGroup.GetColor())
# ----------------------------------------------------------------------------
# methods specific to the standalone group and not present in GroupOnGeometry
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
]
filt = smesh.GetFilterFromCriteria( critaria )
filtGroup = mesh.GroupOnFilter( SMESH.FACE, "group on filter", filt )
- print "Group on filter contains %s elemens" % filtGroup.Size()
+ print("Group on filter contains %s elemens" % filtGroup.Size())
# group on filter is updated if the mesh is modified
hyp1D.SetStartLength( 2.5 )
hyp1D.SetEndLength( 2.5 )
mesh.Compute()
- print "After mesh change, group on filter contains %s elemens" % filtGroup.Size()
+ print("After mesh change, group on filter contains %s elemens" % filtGroup.Size())
# set a new filter defining the group
filt2 = smesh.GetFilter( SMESH.FACE, SMESH.FT_RangeOfIds, "1-50" )
filtGroup.SetFilter( filt2 )
- print "With a new filter, group on filter contains %s elemens" % filtGroup.Size()
+ print("With a new filter, group on filter contains %s elemens" % filtGroup.Size())
# group is updated at modification of the filter
filt2.SetCriteria( [ smesh.GetCriterion( SMESH.FACE, SMESH.FT_RangeOfIds, "1-70" )])
filtIDs3 = filtGroup.GetIDs()
- print "After filter modification, group on filter contains %s elemens" % filtGroup.Size()
+ print("After filter modification, group on filter contains %s elemens" % filtGroup.Size())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area > 35, Nb = ", len(anIds)
+ print("Criterion: Area > 35, Nb = ", len(anIds))
# create a group by adding elements with area > 35
aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Area > 35")
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area > 40, Nb = ", len(anIds)
+ print("Criterion: Area > 40, Nb = ", len(anIds))
# create a group of elements with area [35; 40] by removing elements with area > 40 from group aGroup
aGroup.Remove(anIds)
# print the result
aGroupElemIDs = aGroup.GetListOfID()
- print "Criterion: 35 < Area < 40, Nb = ", len(aGroupElemIDs)
+ print("Criterion: 35 < Area < 40, Nb = ", len(aGroupElemIDs))
j = 1
for i in range(len(aGroupElemIDs)):
- if j > 20: j = 1; print ""
- print aGroupElemIDs[i],
+ if j > 20: j = 1; print("")
+ print(aGroupElemIDs[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area > 20, Nb = ", len( anIds )
+ print("Criterion: Area > 20, Nb = ", len( anIds ))
# create a group by adding elements with area > 20
aGroup1 = mesh.CreateEmptyGroup(SMESH.FACE, "Area > 20")
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area = 20, Nb = ", len( anIds )
+ print("Criterion: Area = 20, Nb = ", len( anIds ))
# create a group by adding elements with area = 20
aGroup2 = mesh.CreateEmptyGroup( SMESH.FACE, "Area = 20" )
# create union group : area >= 20
aGroup3 = mesh.UnionListOfGroups([aGroup1, aGroup2], "Area >= 20")
aGroup3.SetColor( SALOMEDS.Color(1.,1.,0.));
- print "Criterion: Area >= 20, Nb = ", len(aGroup3.GetListOfID())
+ print("Criterion: Area >= 20, Nb = ", len(aGroup3.GetListOfID()))
# Please note that also there is UnionGroups() method which works with two groups only
# Criterion : AREA < 20
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area < 20, Nb = ", len(anIds)
+ print("Criterion: Area < 20, Nb = ", len(anIds))
# create a group by adding elements with area < 20
aGroup4 = mesh.CreateEmptyGroup(SMESH.FACE, "Area < 20")
# create union group : area >= 20 and area < 20
aGroup5 = mesh.UnionListOfGroups([aGroup3, aGroup4], "Any Area")
- print "Criterion: Any Area, Nb = ", len(aGroup5.GetListOfID())
+ print("Criterion: Any Area, Nb = ", len(aGroup5.GetListOfID()))
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area > 20, Nb = ", len(anIds)
+ print("Criterion: Area > 20, Nb = ", len(anIds))
# create a group by adding elements with area > 20
aGroup1 = mesh.CreateEmptyGroup(SMESH.FACE, "Area > 20")
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area < 60, Nb = ", len(anIds)
+ print("Criterion: Area < 60, Nb = ", len(anIds))
# create a group by adding elements with area < 60
aGroup2 = mesh.CreateEmptyGroup(SMESH.FACE, "Area < 60")
# create an intersection of groups : 20 < area < 60
aGroup3 = mesh.IntersectListOfGroups([aGroup1, aGroup2], "20 < Area < 60")
- print "Criterion: 20 < Area < 60, Nb = ", len(aGroup3.GetListOfID())
+ print("Criterion: 20 < Area < 60, Nb = ", len(aGroup3.GetListOfID()))
# Please note that also there is IntersectGroups() method which works with two groups only
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area > 20, Nb = ", len(anIds)
+ print("Criterion: Area > 20, Nb = ", len(anIds))
# create a group by adding elements with area > 20
aGroupMain = mesh.MakeGroupByIds("Area > 20", SMESH.FACE, anIds)
anIds = mesh.GetIdsFromFilter(aFilter)
- print "Criterion: Area < 60, Nb = ", len(anIds)
+ print("Criterion: Area < 60, Nb = ", len(anIds))
# create a group by adding elements with area < 60
aGroupTool = mesh.MakeGroupByIds("Area < 60", SMESH.FACE, anIds)
# create a cut of groups : area >= 60
aGroupRes = mesh.CutGroups(aGroupMain, aGroupTool, "Area >= 60")
- print "Criterion: Area >= 60, Nb = ", len(aGroupRes.GetListOfID())
+ print("Criterion: Area >= 60, Nb = ", len(aGroupRes.GetListOfID()))
# Please note that also there is CutListOfGroups() method which works with lists of groups of any lengths
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
# create a group by adding elements with area > 100
aSrcGroup1 = mesh.GroupOnFilter(SMESH.FACE, "Area > 100", aFilter)
aSrcGroup1.SetColor( SALOMEDS.Color(1.,1.,0.))
- print "Criterion: Area > 100, Nb = ", aSrcGroup1.Size()
+ print("Criterion: Area > 100, Nb = ", aSrcGroup1.Size())
# Criterion : AREA < 30
aFilter = smesh.GetFilter(SMESH.FACE, SMESH.FT_Area, SMESH.FT_LessThan, 30.)
# create a group by adding elements with area < 30
aSrcGroup2 = mesh.GroupOnFilter(SMESH.FACE, "Area < 30", aFilter)
aSrcGroup2.SetColor( SALOMEDS.Color(1.,0.,0.))
- print "Criterion: Area < 30, Nb = ", aSrcGroup2.Size()
+ print("Criterion: Area < 30, Nb = ", aSrcGroup2.Size())
# Create group of edges using source groups of faces
# Create group of nodes using source groups of faces
aGrp = mesh.CreateDimGroup( [aSrcGroup1, aSrcGroup2], SMESH.NODE, "Nodes" )
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a box
box = geompy.MakeBoxDXDYDZ(100,100,100)
# compute basic properties
- print "Get basic properties: approach 1 (via measurements tool) ----"
+ print("Get basic properties: approach 1 (via measurements tool) ----")
measure = smesh.CreateMeasurements()
- print "* for mesh:"
- print " length:", measure.Length(mesh.mesh)
- print " area:", measure.Area(mesh.mesh)
- print " volume:", measure.Volume(mesh.mesh)
+ print("* for mesh:")
+ print(" length:", measure.Length(mesh.mesh))
+ print(" area:", measure.Area(mesh.mesh))
+ print(" volume:", measure.Volume(mesh.mesh))
- print "* for group (2d):"
- print " length:", measure.Length(group_2d)
- print " area:", measure.Area(group_2d)
- print " volume:", measure.Volume(group_2d)
+ print("* for group (2d):")
+ print(" length:", measure.Length(group_2d))
+ print(" area:", measure.Area(group_2d))
+ print(" volume:", measure.Volume(group_2d))
- print "* for submesh (2d):"
- print " length:", measure.Length(submesh_2d_face.GetSubMesh())
- print " area:", measure.Area(submesh_2d_face.GetSubMesh())
- print " volume:", measure.Volume(submesh_2d_face.GetSubMesh())
+ print("* for submesh (2d):")
+ print(" length:", measure.Length(submesh_2d_face.GetSubMesh()))
+ print(" area:", measure.Area(submesh_2d_face.GetSubMesh()))
+ print(" volume:", measure.Volume(submesh_2d_face.GetSubMesh()))
measure.UnRegister()
- print "Get basic properties: approach 2 (via smeshBuilder) ----"
+ print("Get basic properties: approach 2 (via smeshBuilder) ----")
- print "* for mesh:"
- print " length:", smesh.GetLength(mesh)
- print " area:", smesh.GetArea(mesh)
- print " volume:", smesh.GetVolume(mesh)
+ print("* for mesh:")
+ print(" length:", smesh.GetLength(mesh))
+ print(" area:", smesh.GetArea(mesh))
+ print(" volume:", smesh.GetVolume(mesh))
- print "* for group (2d):"
- print " length:", smesh.GetLength(group_2d)
- print " area:", smesh.GetArea(group_2d)
- print " volume:", smesh.GetVolume(group_2d)
+ print("* for group (2d):")
+ print(" length:", smesh.GetLength(group_2d))
+ print(" area:", smesh.GetArea(group_2d))
+ print(" volume:", smesh.GetVolume(group_2d))
- print "* for submesh (2d):"
- print " length:", smesh.GetLength(submesh_2d_face)
- print " area:", smesh.GetArea(submesh_2d_face)
- print " volume:", smesh.GetVolume(submesh_2d_face)
+ print("* for submesh (2d):")
+ print(" length:", smesh.GetLength(submesh_2d_face))
+ print(" area:", smesh.GetArea(submesh_2d_face))
+ print(" volume:", smesh.GetVolume(submesh_2d_face))
- print "Get basic properties: approach 3 (via smeshBuilder.Mesh) ----"
+ print("Get basic properties: approach 3 (via smeshBuilder.Mesh) ----")
- print "* for mesh:"
- print " length:", mesh.GetLength()
- print " area:", mesh.GetArea()
- print " volume:", mesh.GetVolume()
+ print("* for mesh:")
+ print(" length:", mesh.GetLength())
+ print(" area:", mesh.GetArea())
+ print(" volume:", mesh.GetVolume())
- print "* for group (2d): unsupported"
+ print("* for group (2d): unsupported")
- print "* for submesh (2d): unsupported"
+ print("* for submesh (2d): unsupported")
salome.salome_init()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
mesh = smesh.Mesh()
# add node
new_id = mesh.AddNode(50, 10, 0)
- print ""
- if new_id == 0: print "KO node addition."
- else: print "New Node has been added with ID ", new_id
+ print("")
+ if new_id == 0: print("KO node addition.")
+ else: print("New Node has been added with ID ", new_id)
salome.salome_init()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
mesh = smesh.Mesh()
# add 0D Element
new_id = mesh.Add0DElement(node_id)
- print ""
- if new_id == 0: print "KO node addition."
- else: print "New 0D Element has been added with ID ", new_id
+ print("")
+ if new_id == 0: print("KO node addition.")
+ else: print("New 0D Element has been added with ID ", new_id)
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a geometry
mesh.RemoveElements( mesh.GetElementsByType( SMESH.ELEM0D ))
# create 0D elements on some nodes
- nodes = range(1,10)
+ nodes = list(range(1,10))
res = mesh.Add0DElementsToAllNodes( mesh.GetIDSource( nodes, SMESH.NODE ))
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
box = geompy.MakeBoxDXDYDZ(200, 200, 200)
pass
if not node000:
- raise "node000 not found"
+ raise Exception("node000 not found")
# find node000 using a dedicated function
n = mesh.FindNodeClosestTo( -1,-1,-1 )
if not n == node000:
- raise "FindNodeClosestTo() returns " + str( n ) + " != " + str( node000 )
+ raise Exception("FindNodeClosestTo() returns " + str( n ) + " != " + str( node000 ))
# move node000 to a new location
x,y,z = -10, -10, -10
n = mesh.MoveNode( n,x,y,z )
if not n:
- raise "MoveNode() returns " + n
+ raise Exception("MoveNode() returns " + n)
# check the coordinates of the node000
xyz = mesh.GetNodeXYZ( node000 )
if not ( xyz[0] == x and xyz[1] == y and xyz[2] == z) :
- raise "Wrong coordinates: " + str( xyz ) + " != " + str( [x,y,z] )
+ raise Exception("Wrong coordinates: " + str( xyz ) + " != " + str( [x,y,z] ))
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
ff[5] = mesh.AddFace([bb[2], tt[3], tt[2]])
# inverse the diagonal bb[1] - tt[2]
- print "\nDiagonal inversion ... ",
+ print("\nDiagonal inversion ... ", end=' ')
res = mesh.InverseDiag(bb[1], tt[2])
- if not res: print "failed!"
- else: print "done."
+ if not res: print("failed!")
+ else: print("done.")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
ff[5] = mesh.AddFace([bb[2], tt[3], tt[2]])
# delete the diagonal bb[1] - tt[2]
- print "\nUnite two triangles ... ",
+ print("\nUnite two triangles ... ", end=' ')
res = mesh.DeleteDiag(bb[1], tt[2])
- if not res: print "failed!"
- else: print "done."
+ if not res: print("failed!")
+ else: print("done.")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
ff[5] = mesh.AddFace([bb[2], tt[3], tt[2]])
# unite a set of triangles
- print "\nUnite a set of triangles ... ",
+ print("\nUnite a set of triangles ... ", end=' ')
res = mesh.TriToQuad([ff[2], ff[3], ff[4], ff[5]], SMESH.FT_MinimumAngle, 60.)
- if not res: print "failed!"
- else: print "done."
+ if not res: print("failed!")
+ else: print("done.")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import SMESH_mechanic
# boolean SmoothObject(Object, IDsOfFixedNodes, MaxNbOfIterations, MaxAspectRatio, Method)
res = mesh.SmoothObject(GroupSmooth, [], 20, 2., smesh.CENTROIDAL_SMOOTH)
- print "\nSmoothing ... ",
- if not res: print "failed!"
- else: print "done."
+ print("\nSmoothing ... ", end=' ')
+ if not res: print("failed!")
+ else: print("done.")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# 1. Create points
points = [[0, 0], [50, 30], [50, 110], [0, 150], [-80, 150], [-130, 70], [-130, -20]]
vertices = []
for point in points:
vert = geompy.MakeVertex(point[0], point[1], 0)
- geompy.addToStudy(vert, "Vertex_" + `iv`)
+ geompy.addToStudy(vert, "Vertex_" + repr(iv))
vertices.append(vert)
iv += 1
pass
# 3. Explode wire on edges, as they will be used for mesh extrusion
Wire_polyline_edges = geompy.SubShapeAll(Wire_polyline, geompy.ShapeType["EDGE"])
for ii in range(len(Wire_polyline_edges)):
- geompy.addToStudyInFather(Wire_polyline, Wire_polyline_edges[ii], "Edge_" + `ii + 1`)
+ geompy.addToStudyInFather(Wire_polyline, Wire_polyline_edges[ii], "Edge_" + repr(ii + 1))
pass
# Mesh
algo = mesh1d_tool.Segment()
hyp = algo.NumberOfSegments(nbSeg)
isDone = mesh1d_tool.Compute()
- if not isDone: print 'Mesh ', name, ': computation failed'
+ if not isDone: print('Mesh ', name, ': computation failed')
return mesh1d_tool
# Create a mesh with six nodes, seven edges and two quadrangle faces
error = quad_7.ExtrusionAlongPath(ff_7, Edge_Circle_mesh, Edge_Circle, 1,
1, [a45, -a45, a45, -a45, a45, -a45, a45, -a45], 0, refPoint)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# define the geometry
Box_1 = geompy.MakeBoxDXDYDZ(200., 200., 200.)
Mesh_1.Quadrangle()
isDone = Mesh_1.Compute()
- if not isDone: print 'Mesh Mesh_1 : computation failed'
+ if not isDone: print('Mesh Mesh_1 : computation failed')
# build a triangle mesh on Face_2
Mesh_2 = smesh.Mesh(Face_2)
algo2D.MaxElementArea(240)
isDone = Mesh_2.Compute()
- if not isDone: print 'Mesh Mesh_2 : computation failed'
+ if not isDone: print('Mesh Mesh_2 : computation failed')
# create a 2d pattern
pattern = smesh.GetPattern()
isDone = pattern.LoadFromFace(Mesh_2.GetMesh(), Face_2, 0)
- if (isDone != 1): print 'LoadFromFace :', pattern.GetErrorCode()
+ if (isDone != 1): print('LoadFromFace :', pattern.GetErrorCode())
# apply the pattern to a face of the first mesh
facesToSplit = Mesh_1.GetElementsByType(SMESH.FACE)
- print "Splitting %d rectangular face(s) to %d triangles..."%(len(facesToSplit), 2*len(facesToSplit))
+ print("Splitting %d rectangular face(s) to %d triangles..."%(len(facesToSplit), 2*len(facesToSplit)))
pattern.ApplyToMeshFaces(Mesh_1.GetMesh(), facesToSplit, 0, 0)
isDone = pattern.MakeMesh(Mesh_1.GetMesh(), 0, 0)
- if (isDone != 1): print 'MakeMesh :', pattern.GetErrorCode()
+ if (isDone != 1): print('MakeMesh :', pattern.GetErrorCode())
# create quadrangle mesh
Mesh_3 = smesh.Mesh(Box_1)
Mesh_3.Quadrangle()
Mesh_3.Hexahedron()
isDone = Mesh_3.Compute()
- if not isDone: print 'Mesh Mesh_3 : computation failed'
+ if not isDone: print('Mesh Mesh_3 : computation failed')
# create a 3d pattern (hexahedrons)
pattern_hexa = smesh.GetPattern()
# apply the pattern to a mesh
volsToSplit = Mesh_3.GetElementsByType(SMESH.VOLUME)
- print "Splitting %d hexa volume(s) to %d hexas..."%(len(volsToSplit), 4*len(volsToSplit))
+ print("Splitting %d hexa volume(s) to %d hexas..."%(len(volsToSplit), 4*len(volsToSplit)))
pattern_hexa.ApplyToHexahedrons(Mesh_3.GetMesh(), volsToSplit,0,3)
isDone = pattern_hexa.MakeMesh(Mesh_3.GetMesh(), True, True)
- if (isDone != 1): print 'MakeMesh :', pattern_hexa.GetErrorCode()
+ if (isDone != 1): print('MakeMesh :', pattern_hexa.GetErrorCode())
# create one more quadrangle mesh
Mesh_4 = smesh.Mesh(Box_1)
Mesh_4.Quadrangle()
Mesh_4.Hexahedron()
isDone = Mesh_4.Compute()
- if not isDone: print 'Mesh Mesh_4 : computation failed'
+ if not isDone: print('Mesh Mesh_4 : computation failed')
# create another 3d pattern (pyramids)
pattern_pyra = smesh.GetPattern()
# apply the pattern to a face mesh
volsToSplit = Mesh_4.GetElementsByType(SMESH.VOLUME)
- print "Splitting %d hexa volume(s) to %d hexas..."%(len(volsToSplit), 6*len(volsToSplit))
+ print("Splitting %d hexa volume(s) to %d hexas..."%(len(volsToSplit), 6*len(volsToSplit)))
pattern_pyra.ApplyToHexahedrons(Mesh_4.GetMesh(), volsToSplit,1,0)
isDone = pattern_pyra.MakeMesh(Mesh_4.GetMesh(), True, True)
- if (isDone != 1): print 'MakeMesh :', pattern_pyra.GetErrorCode()
+ if (isDone != 1): print('MakeMesh :', pattern_pyra.GetErrorCode())
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create open shell: a box without one plane
box = geompy.MakeBox(0., 0., 0., 20., 20., 15.)
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Free borders Nb = ", len(anIds)
+ print("Criterion: Free borders Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
aGroup = mesh.GetMesh().CreateGroup(SMESH.EDGE, "Free borders")
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create open shell: a box without one plane
box = geompy.MakeBox(0., 0., 0., 20., 20., 15.)
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Borders at multi-connections Nb = ", len(anIds)
+ print("Criterion: Borders at multi-connections Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
aGroup = mesh.GetMesh().CreateGroup(SMESH.EDGE, "Borders at multi-connections")
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create open shell: a box without one plane
box = geompy.MakeBox(0., 0., 0., 20., 20., 15.)
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Edges length > ", length_margin, " Nb = ", len(anIds)
+ print("Criterion: Edges length > ", length_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.GetMesh().CreateGroup(SMESH.EDGE, "Edges with length > " + `length_margin`)
+ aGroup = mesh.GetMesh().CreateGroup(SMESH.EDGE, "Edges with length > " + repr(length_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
aGroupN = mesh.CreateEmptyGroup(SMESH.NODE, "Nodes on free edges")
# fill groups with elements, corresponding to the criterion
- print ""
- print "Criterion: Free edges Nb = ", len(aBorders)
+ print("")
+ print("Criterion: Free edges Nb = ", len(aBorders))
for i in range(len(aBorders)):
aBorder = aBorders[i]
- print "Face # ", aBorder.myElemId, " : Edge between nodes (",
- print aBorder.myPnt1, ", ", aBorder.myPnt2, ")"
+ print("Face # ", aBorder.myElemId, " : Edge between nodes (", end=' ')
+ print(aBorder.myPnt1, ", ", aBorder.myPnt2, ")")
aGroupF.Add([aBorder.myElemId])
aGroupN.Add([aBorder.myPnt1, aBorder.myPnt2])
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create box
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
aGroup.Add(anNodeIds)
# print the result
- print "Criterion: Free nodes Nb = ", len(anNodeIds)
+ print("Criterion: Free nodes Nb = ", len(anNodeIds))
j = 1
for i in range(len(anNodeIds)):
- if j > 20: j = 1; print ""
- print anNodeIds[i],
+ if j > 20: j = 1; print("")
+ print(anNodeIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
####### GEOM part ########
aGroup.Add(aFaceIds)
# print the result
- print "Criterion: Free faces Nb = ", len(aFaceIds)
+ print("Criterion: Free faces Nb = ", len(aFaceIds))
j = 1
for i in range(len(aFaceIds)):
- if j > 20: j = 1; print ""
- print aFaceIds[i],
+ if j > 20: j = 1; print("")
+ print(aFaceIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
#filter faces from plane 2
aFilter = smesh.GetFilter(SMESH.FACE, SMESH.FT_BelongToPlane, Plane_2)
aGroup = Mesh_1.CreateEmptyGroup(SMESH.FACE, "Shared_faces")
aGroup.Add(aFaceIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
# remove half of mesh faces from the smallest face
faceFaces = mesh.GetSubMeshElementsId(face)
- faceToRemove = faceFaces[: len(faceFaces)/2]
+ faceToRemove = faceFaces[: len(faceFaces) // 2]
mesh.RemoveElements( faceToRemove )
# make a group of volumes missing the removed faces
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create open shell: a box without one plane
box = geompy.MakeBox(0., 0., 0., 20., 20., 15.)
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Edges length 2D > ", length_margin, " Nb = ", len(anIds)
+ print("Criterion: Edges length 2D > ", length_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Faces with length 2D > " + `length_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Faces with length 2D > " + repr(length_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a compound of two glued boxes
box1 = geompy.MakeBox(0., 0., 0., 20., 20., 15.)
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Borders at multi-connection 2D = ", nb_conn, " Nb = ", len(anIds)
+ print("Criterion: Borders at multi-connection 2D = ", nb_conn, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Borders at multi-connection 2D = " + `nb_conn`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Borders at multi-connection 2D = " + repr(nb_conn))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Area > ", area_margin, " Nb = ", len(anIds)
+ print("Criterion: Area > ", area_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Area > " + `area_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Area > " + repr(area_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Taper > ", taper_margin, " Nb = ", len(anIds)
+ print("Criterion: Taper > ", taper_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Taper > " + `taper_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Taper > " + repr(taper_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Aspect Ratio > ", ar_margin, " Nb = ", len(anIds)
+ print("Criterion: Aspect Ratio > ", ar_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Aspect Ratio > " + `ar_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Aspect Ratio > " + repr(ar_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Minimum Angle < ", min_angle, " Nb = ", len(anIds)
+ print("Criterion: Minimum Angle < ", min_angle, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Minimum Angle < " + `min_angle`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Minimum Angle < " + repr(min_angle))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Warp > ", wa_margin, " Nb = ", len(anIds)
+ print("Criterion: Warp > ", wa_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Warp > " + `wa_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Warp > " + repr(wa_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Skew > ", skew_margin, " Nb = ", len(anIds)
+ print("Criterion: Skew > ", skew_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Skew > " + `skew_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Skew > " + repr(skew_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Element Diameter 2D Ratio > ", mel_2d_margin, " Nb = ", len(anIds)
+ print("Criterion: Element Diameter 2D Ratio > ", mel_2d_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Element Diameter 2D > " + `mel_2d_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Element Diameter 2D > " + repr(mel_2d_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Aspect Ratio 3D > ", ar_margin, " Nb = ", len(anIds)
+ print("Criterion: Aspect Ratio 3D > ", ar_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.VOLUME, "Aspect Ratio 3D > " + `ar_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.VOLUME, "Aspect Ratio 3D > " + repr(ar_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print ""
- print "Criterion: Volume < ", volume_margin, " Nb = ", len(anIds)
+ print("")
+ print("Criterion: Volume < ", volume_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.VOLUME, "Volume < " + `volume_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.VOLUME, "Volume < " + repr(volume_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anIds = mesh.GetIdsFromFilter(aFilter)
# print the result
- print "Criterion: Element Diameter 3D Ratio > ", mel_3d_margin, " Nb = ", len(anIds)
+ print("Criterion: Element Diameter 3D Ratio > ", mel_3d_margin, " Nb = ", len(anIds))
j = 1
for i in range(len(anIds)):
- if j > 20: j = 1; print ""
- print anIds[i],
+ if j > 20: j = 1; print("")
+ print(anIds[i], end=' ')
j = j + 1
pass
- print ""
+ print("")
# create a group
- aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Element Diameter 3D > " + `mel_3d_margin`)
+ aGroup = mesh.CreateEmptyGroup(SMESH.FACE, "Element Diameter 3D > " + repr(mel_3d_margin))
aGroup.Add(anIds)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a face to be meshed
px = geompy.MakeVertex(100., 0. , 0. )
1, 0, [], 0, SMESH.PointStruct(0, 0, 0))
# merge nodes
- print "Number of nodes before MergeNodes:",
+ print("Number of nodes before MergeNodes:", end=' ')
trias.NbNodes()
tolerance = 0.001
array_of_nodes_groups = trias.FindCoincidentNodes(tolerance)
trias.MergeNodes(array_of_nodes_groups)
- print "Number of nodes after MergeNodes:", trias.NbNodes()
- print ""
- print "Number of elements before MergeEqualElements:"
- print "Edges : ", trias.NbEdges()
- print "Triangles : ", trias.NbTriangles()
- print "Quadrangles: ", trias.NbQuadrangles()
- print "Volumes : ", trias.NbVolumes()
+ print("Number of nodes after MergeNodes:", trias.NbNodes())
+ print("")
+ print("Number of elements before MergeEqualElements:")
+ print("Edges : ", trias.NbEdges())
+ print("Triangles : ", trias.NbTriangles())
+ print("Quadrangles: ", trias.NbQuadrangles())
+ print("Volumes : ", trias.NbVolumes())
# merge elements
trias.MergeEqualElements()
- print "Number of elements after MergeEqualElements:"
- print "Edges : ", trias.NbEdges()
- print "Triangles : ", trias.NbTriangles()
- print "Quadrangles: ", trias.NbQuadrangles()
- print "Volumes : ", trias.NbVolumes()
+ print("Number of elements after MergeEqualElements:")
+ print("Edges : ", trias.NbEdges())
+ print("Triangles : ", trias.NbTriangles())
+ print("Quadrangles: ", trias.NbQuadrangles())
+ print("Volumes : ", trias.NbVolumes())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# make two not sewed quadranges
OY0 = geompy.MakeVectorDXDYDZ(0, 1, 0)
res = mesh.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
FirstNodeID2, SecondNodeID2, LastNodeID2,
CreatePolygons, CreatePolyedrs )
- print res
- print "nb polygons:", mesh.NbPolygons()
+ print(res)
+ print("nb polygons:", mesh.NbPolygons())
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create two boxes
box1 = geompy.MakeBox(0., 0., 0., 10., 10., 10.)
# find elements to sew
face1 = geompy.GetFaceNearPoint( aComp, geompy.MakeVertex( 5, 10, 5 ))
IDsOfSide1Elements = mesh.GetSubMeshElementsId( face1 )
- print "side faces 1:",IDsOfSide1Elements
+ print("side faces 1:",IDsOfSide1Elements)
face1Translated = geompy.MakeTranslation( face1, 0,5,0 )
faceFilter = smesh.GetFilter( SMESH.FACE, SMESH.FT_BelongToGeom,'=', face1Translated )
IDsOfSide2Elements = mesh.GetIdsFromFilter( faceFilter )
- print "side faces 2:",IDsOfSide2Elements
+ print("side faces 2:",IDsOfSide2Elements)
# find corresponding nodes on sides
edge1 = geompy.GetEdgeNearPoint( aComp, geompy.MakeVertex( 0, 10, 5 ))
segs1 = mesh.GetSubMeshElementsId( edge1 ) # mesh segments generated on edge1
NodeID1OfSide1ToMerge = mesh.GetElemNode( segs1[0], 0 )
NodeID2OfSide1ToMerge = mesh.GetElemNode( segs1[0], 1 )
- print "nodes of side1:", [NodeID1OfSide1ToMerge,NodeID2OfSide1ToMerge]
+ print("nodes of side1:", [NodeID1OfSide1ToMerge,NodeID2OfSide1ToMerge])
edge2 = geompy.GetEdgeNearPoint( aComp, geompy.MakeVertex( 0, 15, 5 ))
segs2 = mesh.GetSubMeshElementsId( edge2 ) # mesh segments generated on edge2
NodeID1OfSide2ToMerge = mesh.GetElemNode( segs2[0], 0 )
NodeID2OfSide2ToMerge = mesh.GetElemNode( segs2[0], 1 )
- print "nodes of side2:", [NodeID1OfSide2ToMerge,NodeID2OfSide2ToMerge]
+ print("nodes of side2:", [NodeID1OfSide2ToMerge,NodeID2OfSide2ToMerge])
res = mesh.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
- print res
+ print(res)
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# Create a box
faces1.Add( [ 144, 151, 158 ] )
# Duplicate nodes
- print "\nMesh before the first nodes duplication:"
- print "Nodes : ", mesh.NbNodes()
- print "Edges : ", mesh.NbEdges()
- print "Quadrangles : ", mesh.NbQuadrangles()
+ print("\nMesh before the first nodes duplication:")
+ print("Nodes : ", mesh.NbNodes())
+ print("Edges : ", mesh.NbEdges())
+ print("Quadrangles : ", mesh.NbQuadrangles())
groupOfCreatedNodes = mesh.DoubleNodeGroup(nodes1, faces1, theMakeGroup=True)
- print "New nodes:", groupOfCreatedNodes.GetIDs()
+ print("New nodes:", groupOfCreatedNodes.GetIDs())
- print "\nMesh after the first nodes duplication:"
- print "Nodes : ", mesh.NbNodes()
- print "Edges : ", mesh.NbEdges()
- print "Quadrangles : ", mesh.NbQuadrangles()
+ print("\nMesh after the first nodes duplication:")
+ print("Nodes : ", mesh.NbNodes())
+ print("Edges : ", mesh.NbEdges())
+ print("Quadrangles : ", mesh.NbQuadrangles())
# Duplicate nodes and border elements
faces2.Add( [ 141, 148, 155 ] )
# Duplicate nodes
- print "\nMesh before the second nodes duplication:"
- print "Nodes : ", mesh.NbNodes()
- print "Edges : ", mesh.NbEdges()
- print "Quadrangles : ", mesh.NbQuadrangles()
+ print("\nMesh before the second nodes duplication:")
+ print("Nodes : ", mesh.NbNodes())
+ print("Edges : ", mesh.NbEdges())
+ print("Quadrangles : ", mesh.NbQuadrangles())
groupOfNewEdges = mesh.DoubleNodeElemGroup( edges, nodes2, faces2, theMakeGroup=True )
- print "New edges:", groupOfNewEdges.GetIDs()
+ print("New edges:", groupOfNewEdges.GetIDs())
- print "\nMesh after the second nodes duplication:"
- print "Nodes : ", mesh.NbNodes()
- print "Edges : ", mesh.NbEdges()
- print "Quadrangles : ", mesh.NbQuadrangles()
+ print("\nMesh after the second nodes duplication:")
+ print("Nodes : ", mesh.NbNodes())
+ print("Edges : ", mesh.NbEdges())
+ print("Quadrangles : ", mesh.NbQuadrangles())
# Duplicate elements only
# Update object browser
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(False)
+ salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
# remove some faces
faces = init_mesh.GetElementsByType( SMESH.FACE )
nb_faces = len( faces )
- rm_face = faces[ : nb_faces/2]
+ rm_face = faces[ : nb_faces // 2]
init_mesh.RemoveElements( rm_face )
# restore boundary in this mesh
# remove some edges
edges = init_mesh.GetElementsByType( SMESH.EDGE )
nb_edges = len( edges )
- rm_edge = edges[ : nb_edges/2]
+ rm_edge = edges[ : nb_edges // 2]
init_mesh.RemoveElements( rm_edge )
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import salome_notebook
# pass group0 and ids of faces of group1 to inverse
nbRev = mesh3D.Reorient2DBy3D([ group0, group1.GetIDs() ], mesh3D, theOutsideNormal=False)
- print "Nb reoriented faces:", nbRev
+ print("Nb reoriented faces:", nbRev)
# orient the reversed faces back
nbRev = mesh3D.Reorient2DBy3D( mesh3D, mesh3D, theOutsideNormal=True)
- print "Nb re-reoriented faces:", nbRev
+ print("Nb re-reoriented faces:", nbRev)
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# create a box
box = geompy.MakeBox(0., 0., 0., 20., 20., 20.)
nbAdd = group.Add( [ 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 ] )
# Print information about the mesh
- print "Information about mesh:"
- print "Number of nodes : ", tetra.NbNodes()
- print "Number of edges : ", tetra.NbEdges()
- print "Number of faces : ", tetra.NbFaces()
- print " triangles : ", tetra.NbTriangles()
- print " quadrangles : ", tetra.NbQuadrangles()
- print " polygons : ", tetra.NbPolygons()
- print "Number of volumes : ", tetra.NbVolumes()
- print " tetrahedrons: ", tetra.NbTetras()
- print " hexahedrons : ", tetra.NbHexas()
- print " prisms : ", tetra.NbPrisms()
- print " pyramids : ", tetra.NbPyramids()
- print " polyhedrons : ", tetra.NbPolyhedrons()
+ print("Information about mesh:")
+ print("Number of nodes : ", tetra.NbNodes())
+ print("Number of edges : ", tetra.NbEdges())
+ print("Number of faces : ", tetra.NbFaces())
+ print(" triangles : ", tetra.NbTriangles())
+ print(" quadrangles : ", tetra.NbQuadrangles())
+ print(" polygons : ", tetra.NbPolygons())
+ print("Number of volumes : ", tetra.NbVolumes())
+ print(" tetrahedrons: ", tetra.NbTetras())
+ print(" hexahedrons : ", tetra.NbHexas())
+ print(" prisms : ", tetra.NbPrisms())
+ print(" pyramids : ", tetra.NbPyramids())
+ print(" polyhedrons : ", tetra.NbPolyhedrons())
# Get Information About Mesh by GetMeshInfo
- print "\nInformation about mesh by GetMeshInfo:"
+ print("\nInformation about mesh by GetMeshInfo:")
info = smesh.GetMeshInfo(tetra)
- keys = info.keys(); keys.sort()
+ keys = list(info.keys()); keys.sort()
for i in keys:
- print " %s : %d" % ( i, info[i] )
+ print(" %s : %d" % ( i, info[i] ))
pass
# Get Information About Group by GetMeshInfo
- print "\nInformation about group by GetMeshInfo:"
+ print("\nInformation about group by GetMeshInfo:")
info = smesh.GetMeshInfo(group)
- keys = info.keys(); keys.sort()
+ keys = list(info.keys()); keys.sort()
for i in keys:
- print " %s : %d" % ( i, info[i] )
+ print(" %s : %d" % ( i, info[i] ))
pass
# Get Information About SubMesh by GetMeshInfo
- print "\nInformation about Submesh by GetMeshInfo:"
+ print("\nInformation about Submesh by GetMeshInfo:")
info = smesh.GetMeshInfo(submesh)
- keys = info.keys(); keys.sort()
+ keys = list(info.keys()); keys.sort()
for i in keys:
- print " %s : %d" % ( i, info[i] )
+ print(" %s : %d" % ( i, info[i] ))
pass
typedef sequence<SMESH_subMesh> submesh_array;
typedef sequence<submesh_array> submesh_array_array;
- interface SMESH_Mesh : SALOME::GenericObj, SMESH_IDSource
+ interface SMESH_Mesh : SMESH_IDSource
{
/*!
* Return true if there is a geometry to be meshed
*/
long GetId();
- /*!
- * Get the study Id
- */
- long GetStudyId();
-
/*!
* Obtain instance of SMESH_MeshEditor
*/
*/
long FindElementByNodes(in long_array nodes);
+ /*!
+ * Return elements including all given nodes.
+ */
+ long_array GetElementsByNodes(in long_array nodes, in ElementType elem_type);
+
/*!
* Returns true if given element is polygon
*/
string_array GetLastParameters();
};
- interface SMESH_subMesh : SALOME::GenericObj, SMESH_IDSource
+ interface SMESH_subMesh : SMESH_IDSource
{
/*!
*
//=============================================================================
SMESH_Mesh::SMESH_Mesh(int theLocalId,
- int theStudyId,
SMESH_Gen* theGen,
bool theIsEmbeddedMode,
SMESHDS_Document* theDocument):
{
if(MYDEBUG) MESSAGE("SMESH_Mesh::SMESH_Mesh(int localId)");
_id = theLocalId;
- _studyId = theStudyId;
_gen = theGen;
_myDocument = theDocument;
_myMeshDS = theDocument->NewMesh(theIsEmbeddedMode,theLocalId);
SMESH_Mesh::SMESH_Mesh():
_id(-1),
- _studyId(-1),
_groupId( 0 ),
_nbSubShapes( 0 ),
_isShapeToMesh( false ),
// remove self from studyContext
if ( _gen )
{
- StudyContextStruct * studyContext = _gen->GetStudyContext( _studyId );
+ StudyContextStruct * studyContext = _gen->GetStudyContext();
studyContext->mapMesh.erase( _id );
}
if ( _myDocument )
if ( _id == meshId )
return (SMESH_Mesh*) this;
- if ( StudyContextStruct *aStudyContext = _gen->GetStudyContext( _studyId ))
+ if ( StudyContextStruct *aStudyContext = _gen->GetStudyContext())
{
std::map < int, SMESH_Mesh * >::iterator i_m = aStudyContext->mapMesh.find( meshId );
if ( i_m != aStudyContext->mapMesh.end() )
Unexpect aCatch(SalomeException);
if(MYDEBUG) MESSAGE("SMESH_Mesh::RemoveHypothesis");
- StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
+ StudyContextStruct *sc = _gen->GetStudyContext();
if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
throw SALOME_Exception(LOCALIZED("hypothesis does not exist"));
SMESH_Hypothesis * SMESH_Mesh::GetHypothesis(const int anHypId) const
{
- StudyContextStruct *sc = _gen->GetStudyContext(_studyId);
+ StudyContextStruct *sc = _gen->GetStudyContext();
if (sc->mapHypothesis.find(anHypId) == sc->mapHypothesis.end())
return NULL;
#ifdef WIN32
cmd = "%PYTHONBIN% ";
#else
- cmd = "python ";
+ cmd = "python3 ";
#endif
cmd += "-c \"";
cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
#ifdef WIN32
cmd = "%PYTHONBIN% ";
#else
- cmd = "python ";
+ cmd = "python3 ";
#endif
cmd += "-c \"";
cmd += "from medutilities import convert ; convert(r'" + medfilename + "', 'MED', 'GIBI', 1, r'" + file + "')";
#ifdef WIN32
cmd = "%PYTHONBIN% ";
#else
- cmd = "python ";
+ cmd = "python3 ";
#endif
cmd += "-c \"";
cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
_AString comment;
_pyID obj = cmd->GetObject();
- if ( obj.Search( "print " ) == 1 )
+ if ( obj.Search( "print(" ) == 1 )
return; // print statement
if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
std::set< TCollection_AsciiString >& theRemovedObjIDs,
- SALOMEDS::Study_ptr& theStudy,
const bool theToKeepAllCommands)
{
std::list< TCollection_AsciiString >::iterator lineIt;
theGen = new _pyGen( theEntry2AccessorMethod,
theObjectNames,
theRemovedObjIDs,
- theStudy,
theToKeepAllCommands );
for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
set<_pyID> createdObjects;
createdObjects.insert( "smeshBuilder" );
createdObjects.insert( "smesh" );
- createdObjects.insert( "theStudy" );
for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
{
#ifdef DUMP_CONVERSION
_pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
std::set< TCollection_AsciiString >& theRemovedObjIDs,
- SALOMEDS::Study_ptr& theStudy,
const bool theToKeepAllCommands)
: _pyObject( new _pyCommand( "", 0 )),
myNbCommands( 0 ),
myRemovedObjIDs( theRemovedObjIDs ),
myNbFilters( 0 ),
myToKeepAllCommands( theToKeepAllCommands ),
- myStudy( SALOMEDS::Study::_duplicate( theStudy )),
myGeomIDNb(0), myGeomIDIndex(-1)
{
// make that GetID() to return TPythonDump::SMESHGenName()
GetCreationCmd()->GetString() += "=";
// Find 1st digit of study entry by which a GEOM object differs from a SMESH object
- if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
+ if ( !theObjectNames.IsEmpty() )
{
// find a GEOM entry
_pyID geomID;
- SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
+ SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
if ( geomComp->_is_nil() ) return;
CORBA::String_var entry = geomComp->GetID();
geomID = entry.in();
_AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
_AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
_AString excStr = indent + "except:";
- _AString msgStr = indent + "\tprint '"; msgStr += method + "() failed. Invalid file name?'";
+ _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
aCommand->Clear();
static TStringSet smeshpyMethods;
if ( smeshpyMethods.empty() ) {
const char * names[] =
- { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
+ { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
"GetPattern","GetSubShapesId",
"" }; // <- mark of array end
smeshpyMethods.Insert( names );
// either the SMESH object is not in study or it is a GEOM object
if ( IsGeomObject( theObjID ))
{
- SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
+ SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
if ( so->_is_nil() ) return true;
CORBA::Object_var obj = so->GetObject();
return CORBA::is_nil( obj );
const char * names[] =
{ "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
"GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
- "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
+ "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
"NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
"NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
"NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
_thisObj = this ;
_id = myPoa->activate_object( _thisObj );
+ myStudyContext = new StudyContext;
+
myIsEmbeddedMode = false;
+ myIsEnablePublish = true;
myShapeReader = NULL; // shape reader
mySMESHGen = this;
myIsHistoricalPythonDump = true;
myHypCreatorMap.clear();
// Clear study contexts data
- map<int, StudyContext*>::iterator it;
- for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
- delete it->second;
- }
- myStudyContextMap.clear();
+ delete myStudyContext;
+
// delete shape reader
if ( myShapeReader )
delete myShapeReader;
getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
// create a new hypothesis object, store its ref. in studyContext
- myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
+ myHypothesis_i = aCreator->Create(myPoa, &myGen);
if (myHypothesis_i)
{
myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
// Get or create the GEOM_Client instance
try {
// create a new mesh object servant, store it in a map in study context
- SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
+ SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
// create a new mesh object
if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
- meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
+ meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
// activate the CORBA servant of Mesh
SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
//=============================================================================
/*!
- * SMESH_Gen_i::SetCurrentStudy
+ * SMESH_Gen_i::SetEnablePublish
*
- * Set current study
+ * Set enable publishing in the study
*/
//=============================================================================
-
-void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
+void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
{
- setCurrentStudy( theStudy );
+ myIsEnablePublish = theIsEnablePublish;
}
-void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
- bool theStudyIsBeingClosed)
+//=============================================================================
+/*!
+ * SMESH_Gen_i::IsEnablePublish
+ *
+ * Check enable publishing
+ */
+//=============================================================================
+
+CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
{
- int curStudyId = GetCurrentStudyID();
- myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
- // create study context, if it doesn't exist and set current study
- int studyId = GetCurrentStudyID();
- if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
- myStudyContextMap[ studyId ] = new StudyContext;
-
- // myCurrentStudy may be nil
- if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
- SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
- if( !GEOM_var->_is_nil() )
- aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
- // NPAL16168, issue 0020210
- // Let meshes update their data depending on GEOM groups that could change
- if ( curStudyId != studyId )
- {
- CORBA::String_var compDataType = ComponentDataType();
- SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
- if ( !me->_is_nil() ) {
- SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
- for ( ; anIter->More(); anIter->Next() ) {
- SALOMEDS::SObject_wrap so = anIter->Value();
- CORBA::Object_var ior = SObjectToObject( so );
- if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
- mesh->CheckGeomModif();
- }
- }
- }
- }
+ return myIsEnablePublish;
}
//=============================================================================
/*!
- * SMESH_Gen_i::GetCurrentStudy
+ * SMESH_Gen_i::UpdateStudy
*
- * Get current study
+ * Update study (needed at switching GEOM->SMESH)
*/
//=============================================================================
-SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
+void SMESH_Gen_i::UpdateStudy()
{
- if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
- if ( GetCurrentStudyID() < 0 )
- return SALOMEDS::Study::_nil();
- return SALOMEDS::Study::_duplicate( myCurrentStudy );
+ if ( !myStudyContext )
+ myStudyContext = new StudyContext;
+
+ SALOMEDS::Study_var aStudy = getStudyServant();
+ if ( !CORBA::is_nil( aStudy ) ) {
+ SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
+ SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
+ if( !GEOM_var->_is_nil() )
+ aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
+ // NPAL16168, issue 0020210
+ // Let meshes update their data depending on GEOM groups that could change
+ CORBA::String_var compDataType = ComponentDataType();
+ SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
+ if ( !me->_is_nil() ) {
+ SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
+ for ( ; anIter->More(); anIter->Next() ) {
+ SALOMEDS::SObject_wrap so = anIter->Value();
+ CORBA::Object_var ior = SObjectToObject( so );
+ if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
+ mesh->CheckGeomModif();
+ }
+ }
+ }
}
//=============================================================================
/*!
- * SMESH_Gen_i::GetCurrentStudyContext
+ * SMESH_Gen_i::GetStudyContext
*
- * Get current study context
+ * Get study context
*/
//=============================================================================
-StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
+StudyContext* SMESH_Gen_i::GetStudyContext()
{
- if ( !CORBA::is_nil( myCurrentStudy ) &&
- myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
- return myStudyContextMap[ myCurrentStudy->StudyId() ];
- else
- return 0;
+ return myStudyContext;
}
//=============================================================================
// Publish hypothesis/algorithm in the study
if ( CanPublishInStudy( hyp ) ) {
- SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
+ SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
if ( !aSO->_is_nil() ) {
// Update Python script
TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
SMESH::SMESH_Mesh_out theMesh,
GEOM::GEOM_Object_out theShape)
{
- if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
+ if ( CORBA::is_nil( theHyp ))
return false;
// get Mesh component SO
CORBA::String_var compDataType = ComponentDataType();
- SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
+ SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
if ( CORBA::is_nil( comp ))
return false;
SMESH::SMESH_Mesh_var foundMesh;
TopoDS_Shape foundShape;
bool isSole = true;
- SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
+ SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
for ( ; meshIter->More() && isSole; meshIter->Next() )
{
SALOMEDS::SObject_wrap curSO = meshIter->Value();
// publish mesh in the study
if ( CanPublishInStudy( mesh ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
- SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
+ SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
aStudyBuilder->CommitCommand();
if ( !aSO->_is_nil() ) {
// Update Python script
// publish mesh in the study
if ( CanPublishInStudy( mesh ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
- SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
+ SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
aStudyBuilder->CommitCommand();
if ( !aSO->_is_nil() ) {
// Update Python script
string aFileName;
// publish mesh in the study
if ( CanPublishInStudy( aMesh ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
- SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
+ SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
aStudyBuilder->CommitCommand();
if ( !aSO->_is_nil() ) {
// Update Python script
if (theStatus == SMESH::DRS_OK) {
SALOMEDS::StudyBuilder_var aStudyBuilder;
- if ( GetCurrentStudyID() > -1 )
- {
- aStudyBuilder = myCurrentStudy->NewBuilder();
- aStudyBuilder->NewCommand(); // There is a transaction
- }
+ aStudyBuilder = getStudyServant()->NewBuilder();
+ aStudyBuilder->NewCommand(); // There is a transaction
+
aResult->length( aNames.size() );
int i = 0;
// little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
// - as names of meshes are stored in MED file, we use them for data publishing
// - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
- aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
+ aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
// Python Dump
if ( !aSO->_is_nil() ) {
#ifdef WIN32
cmd = "%PYTHONBIN% ";
#else
- cmd = "python ";
+ cmd = "python3 ";
#endif
cmd += "-c \"";
cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
#ifdef WIN32
cmd = "%PYTHONBIN% ";
#else
- cmd = "python ";
+ cmd = "python3 ";
#endif
cmd += "-c \"";
cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
#endif
// publish mesh in the study
if ( CanPublishInStudy( aMesh ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
- SALOMEDS::SObject_wrap aSO = PublishInStudy
- ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
+ SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
aStudyBuilder->CommitCommand();
if ( !aSO->_is_nil() ) {
// Update Python script
if (theStatus == SMESH::DRS_OK)
{
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
int i = 0;
// publish mesh in the study
SALOMEDS::SObject_wrap aSO;
if ( CanPublishInStudy( mesh ) )
- aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
+ aSO = PublishMesh( mesh.in(), meshName.c_str() );
// Python Dump
if ( !aSO->_is_nil() ) {
#endif
// publish mesh in the study
if ( CanPublishInStudy( aMesh ) ) {
- SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->NewCommand(); // There is a transaction
- SALOMEDS::SObject_wrap aSO = PublishInStudy
- ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
+ SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
aStudyBuilder->CommitCommand();
if ( !aSO->_is_nil() ) {
// Update Python script
SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
{
if ( algo ) {
- if ( !myCurrentStudy->_is_nil() ) {
+ SALOMEDS::Study_var aStudy = getStudyServant();
+ if ( !aStudy->_is_nil() ) {
// find algo in the study
CORBA::String_var compDataType = ComponentDataType();
- SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
+ SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
if ( !father->_is_nil() ) {
- SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
+ SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
for ( ; itBig->More(); itBig->Next() ) {
SALOMEDS::SObject_wrap gotBranch = itBig->Value();
if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
- SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
+ SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
for ( ; algoIt->More(); algoIt->Next() ) {
SALOMEDS::SObject_wrap algoSO = algoIt->Value();
CORBA::Object_var algoIOR = SObjectToObject( algoSO );
GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
// try to find the corresponding SObject
- SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
+ SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
if ( SObj->_is_nil() ) // submesh can be not found even if published
{
// try to find published submesh
GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
if ( !geom->IsMainShape() && list->length() == 1 ) {
- SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
+ SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
SALOMEDS::ChildIterator_wrap it;
if ( !mainSO->_is_nil() ) {
- it = myCurrentStudy->NewChildIterator( mainSO );
+ it = getStudyServant()->NewChildIterator( mainSO );
}
if ( !it->_is_nil() ) {
for ( it->InitEx(true); it->More(); it->Next() ) {
}
}
if ( SObj->_is_nil() ) // publish a new subshape
- SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
+ SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
// return only published geometry
if ( !SObj->_is_nil() ) {
GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
if ( geom->_is_nil() ) {
// try to find a published sub-shape
- SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
+ SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
SALOMEDS::ChildIterator_wrap it;
if ( !mainSO->_is_nil() ) {
- it = myCurrentStudy->NewChildIterator( mainSO );
+ it = getStudyServant()->NewChildIterator( mainSO );
}
if ( !it->_is_nil() ) {
for ( it->InitEx(true); it->More(); it->Next() ) {
}
if ( geom->_is_nil() ) {
// explode
- GEOM::GEOM_IShapesOperations_wrap op =
- geomGen->GetIShapesOperations( GetCurrentStudyID() );
+ GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
if ( !op->_is_nil() )
geom = op->GetSubShape( mainShape, shapeID );
}
const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
{ // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
const int nbNames = sizeof(typeNames) / sizeof(const char*);
- int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1];
+ int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
}
string groupName = "Gr";
- SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
+ SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( theMeshesArray[i] );
if ( aMeshSObj ) {
CORBA::String_var name = aMeshSObj->GetName();
groupName += name;
}
// IPAL21468 Change icon of compound because it need not be computed.
- SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
+ SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( aNewMesh );
SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
if (aNewMeshDS)
SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
if ( !newMesh_i )
THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
- SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
+ SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
if ( !meshSO->_is_nil() )
{
SetName( meshSO, meshName, "Mesh" );
const char* theURL,
bool isMultiFile )
{
- // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
- // san -- in case <myCurrentStudy> differs from theComponent's study,
- // use that of the component
- if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
- SetCurrentStudy( theComponent->GetStudy() );
+ if (!myStudyContext)
+ UpdateStudy();
// Store study contents as a set of python commands
- SavePython(myCurrentStudy);
+ SavePython();
- StudyContext* myStudyContext = GetCurrentStudyContext();
+ SALOMEDS::Study_var aStudy = getStudyServant();
// Declare a byte stream
SALOMEDS::TMPFile_var aStreamFile;
( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
// Create a sequence of files processed
- SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
- aFileSeq->length( NUM_TMP_FILES );
+ SALOMEDS_Tool::ListOfFiles aFileSeq;
+ aFileSeq.reserve( NUM_TMP_FILES );
TCollection_AsciiString aStudyName( "" );
if ( isMultiFile )
- aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( aStudy->URL() ).c_str() );
- aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(myCurrentStudy->URL()) ).c_str() );
++ aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
// Set names of temporary files
TCollection_AsciiString filename =
aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
TCollection_AsciiString meshfile =
aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
- aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
- aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
+ aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
+ aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
filename = tmpDir + filename;
meshfile = tmpDir + meshfile;
// SetStoreName() to groups before storing hypotheses to let them refer to
// groups using "store name", which is "Group <group_persistent_id>"
{
- SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
+ SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
for ( ; itBig->More(); itBig->Next() ) {
SALOMEDS::SObject_wrap gotBranch = itBig->Value();
if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
aFile->CreateOnDisk();
// --> iterator for top-level objects
- SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
+ SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
for ( ; itBig->More(); itBig->Next() ) {
SALOMEDS::SObject_wrap gotBranch = itBig->Value();
aTopGroup->CreateOnDisk();
// iterator for all hypotheses
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySObject = it->Value();
CORBA::Object_var anObject = SObjectToObject( mySObject );
aTopGroup->CreateOnDisk();
// iterator for all algorithms
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySObject = it->Value();
CORBA::Object_var anObject = SObjectToObject( mySObject );
SALOMEDS::SObject_wrap myHypBranch;
found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
if ( found && !shapeRefFound && hasShape) { // remove applied hyps
- myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
+ aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
}
if ( found && (shapeRefFound || !hasShape) ) {
aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
aGroup->CreateOnDisk();
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
int hypNb = 0;
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySObject = it->Value();
found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
myAlgoBranch.inout() );
if ( found && !shapeRefFound && hasShape) { // remove applied algos
- myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
+ aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
}
if ( found && (shapeRefFound || !hasShape)) {
aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
aGroup->CreateOnDisk();
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
int algoNb = 0;
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySObject = it->Value();
{
bool hasShapeRef = false;
SALOMEDS::ChildIterator_wrap itSM =
- myCurrentStudy->NewChildIterator( mySubmeshBranch );
+ aStudy->NewChildIterator( mySubmeshBranch );
for ( ; itSM->More(); itSM->Next() ) {
SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
}
}
}
- myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
+ aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
}
} // loop on submeshes of a type
if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
- myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
+ aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
found = false;
}
} // end check if there is shape reference in submeshes
aGroup->CreateOnDisk();
// iterator for all submeshes of given type
- SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
+ SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
for ( ; itSM->More(); itSM->Next() ) {
SALOMEDS::SObject_wrap mySObject = itSM->Value();
CORBA::Object_var anSubObject = SObjectToObject( mySObject );
aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
aSubSubGroup->CreateOnDisk();
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
int hypNb = 0;
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySubSObject = it->Value();
aSubSubGroup->CreateOnDisk();
SALOMEDS::ChildIterator_wrap it =
- myCurrentStudy->NewChildIterator( mySubAlgoBranch );
+ aStudy->NewChildIterator( mySubAlgoBranch );
int algoNb = 0;
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySubSObject = it->Value();
aGroup = new HDFgroup( name_group, aTopGroup );
aGroup->CreateOnDisk();
- SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
for ( ; it->More(); it->Next() ) {
SALOMEDS::SObject_wrap mySObject = it->Value();
CORBA::Object_var aSubObject = SObjectToObject( mySObject );
delete aFile;
// Convert temporary files to stream
- aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
+ aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
// Remove temporary files and directory
if ( !isMultiFile )
- SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
+ SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
return aStreamFile._retn();
}
if ( theCompRoot->_is_nil() )
return;
- SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
- if ( aStudy->_is_nil() )
- return;
-
- SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
+ SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
}
const char* theURL,
bool isMultiFile )
{
- if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
- SetCurrentStudy( theComponent->GetStudy() );
-
+ if (!myStudyContext)
+ UpdateStudy();
+ SALOMEDS::Study_var aStudy = getStudyServant();
/* if( !theComponent->_is_nil() )
{
- //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
- if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
- loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
+ if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
+ loadGeomData( aStudy->FindComponent( "GEOM" ) );
}*/
- StudyContext* myStudyContext = GetCurrentStudyContext();
-
// Get temporary files location
TCollection_AsciiString tmpDir =
( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
// Convert the stream into sequence of files to process
- SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
- tmpDir.ToCString(),
- isMultiFile );
+ SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
+ tmpDir.ToCString(),
+ isMultiFile );
TCollection_AsciiString aStudyName( "" );
if ( isMultiFile ) {
- CORBA::String_var url = aStudy->URL();
- aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
- CORBA::WString_var url = myCurrentStudy->URL();
++ CORBA::WString_var url = aStudy->URL();
+ aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
}
// Set names of temporary files
TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
aDataset->ReadFromDisk( refFromFile );
aDataset->CloseOnDisk();
if ( strlen( refFromFile ) > 0 ) {
- SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
+ SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
// Make sure GEOM data are loaded first
//loadGeomData( shapeSO->GetFatherComponent() );
aDataset->ReadFromDisk( refFromFile );
aDataset->CloseOnDisk();
// san - it is impossible to recover applied algorithms using their entries within Load() method
- //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
+ //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
//CORBA::Object_var hypObject = SObjectToObject( hypSO );
int id = atoi( refFromFile );
delete [] refFromFile;
aDataset->ReadFromDisk( refFromFile );
aDataset->CloseOnDisk();
// san - it is impossible to recover applied hypotheses using their entries within Load() method
- //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
+ //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
//CORBA::Object_var hypObject = SObjectToObject( hypSO );
int id = atoi( refFromFile );
delete [] refFromFile;
aDataset->ReadFromDisk( refFromFile );
aDataset->CloseOnDisk();
if ( strlen( refFromFile ) > 0 ) {
- SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
+ SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
if ( !CORBA::is_nil( subShapeObject ) ) {
aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
aDataset->ReadFromDisk( refFromFile );
aDataset->CloseOnDisk();
if ( strlen( refFromFile ) > 0 ) {
- SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
+ SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
if ( !CORBA::is_nil( shapeObject ) ) {
aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
SMESH_File meshFile( meshfile.ToCString() );
if ( !meshFile ) // no meshfile exists
{
- SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
+ SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
}
else
{
// creation of tree nodes for all data objects in the study
// to support tree representation customization and drag-n-drop:
- SALOMEDS::Study_var study = theComponent->GetStudy();
- SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
useCaseBuilder->SetRootCurrent();
useCaseBuilder->Append( theComponent ); // component object is added as the top level item
- SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
+ SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
for (it->InitEx(true); it->More(); it->Next()) {
useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
}
{
if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
- // set correct current study
- SALOMEDS::Study_var study = theComponent->GetStudy();
- if ( study->StudyId() != GetCurrentStudyID())
- setCurrentStudy( study, /*IsBeingClosed=*/true );
-
// Clear study contexts data
- int studyId = GetCurrentStudyID();
- if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
- delete myStudyContextMap[ studyId ];
- myStudyContextMap.erase( studyId );
- }
+ delete myStudyContext;
+ myStudyContext = 0;
// remove the tmp files meshes are loaded from
SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
- myCurrentStudy = SALOMEDS::Study::_nil();
return;
}
CORBA::Boolean /*isASCII*/ )
{
if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
- StudyContext* myStudyContext = GetCurrentStudyContext();
if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
int anId = myStudyContext->findId( IORString );
CORBA::Boolean /*isASCII*/ )
{
if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
- StudyContext* myStudyContext = GetCurrentStudyContext();
if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
int anId = atoi( aLocalPersistentID );
int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
{
- StudyContext* myStudyContext = GetCurrentStudyContext();
if ( myStudyContext && !CORBA::is_nil( theObject )) {
CORBA::String_var iorString = GetORB()->object_to_string( theObject );
return myStudyContext->addObject( string( iorString.in() ) );
CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
{
- StudyContext* myStudyContext = GetCurrentStudyContext();
if ( myStudyContext && !CORBA::is_nil( theObject )) {
string iorString = GetORB()->object_to_string( theObject );
return myStudyContext->findId( iorString );
{
if ( theIOR && strcmp( theIOR, "" ) ) {
CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
- SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
+ SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
if ( !aSO->_is_nil() ) {
SetName( aSO, theName );
}
}
}
-int SMESH_Gen_i::GetCurrentStudyID()
-{
- return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
-}
-
// Version information
char* SMESH_Gen_i::getVersion()
{
{
if ( CORBA::is_nil( where ) ) return;
- SALOMEDS::Study_var study = where->GetStudy();
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
SALOMEDS::SComponent_var father = where->GetFatherComponent();
std::string dataType = father->ComponentDataType();
if ( dataType != "SMESH" ) return; // not a SMESH component
## This function updates the tools so that it works on the
# specified study.
- def updateStudy(self, studyId=None):
+ def updateStudy(self):
"""
This function updates the tools so that it works on the
specified study.
"""
- self.editor = getStudyEditor(studyId)
+ self.editor = getStudyEditor()
## Get the mesh item owning the mesh group \em meshGroupItem.
# \param meshGroupItem (SObject) mesh group belonging to the searched mesh.
return None
import SMESH
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(self.editor.study)
+ smesh = smeshBuilder.New()
meshObject=salome.IDToObject(entry)
return smesh.Mesh( meshObject )
self.smeshGui = salome.ImportComponentGUI("SMESH")
if not helper.SalomeGUI.hasDesktop():
- print "displayMeshObject: no desktop available"
+ print("displayMeshObject: no desktop available")
return
self.smeshGui.CreateAndDisplayActor(entry)
def TEST_createBoxMesh():
- theStudy = helper.getActiveStudy()
import GEOM
from salome.geom import geomBuilder
- geompy = geomBuilder.New(theStudy)
+ geompy = geomBuilder.New()
box = geompy.MakeBoxDXDYDZ(200, 200, 200)
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(theStudy)
+ smesh = smeshBuilder.New()
from salome.StdMeshers import StdMeshersBuilder
boxmesh = smesh.Mesh(box)
smesh.SetName(boxmesh.GetMesh(), 'boxmesh')
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(True)
+ salome.sg.updateObjBrowser()
#
# Definitions:
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
#-----------------------------GEOM----------------------------------------
mesh = smesh.Mesh(plane_mesh, "Mesh_1")
- print"---------------------Hypothesis and Algorithms"
+ print("---------------------Hypothesis and Algorithms")
#---------------- NumberOfSegments
algoWireDes = mesh.Segment()
listHyp = algoWireDes.GetCompatibleHypothesis()
- print algoWireDes.GetName()
+ print(algoWireDes.GetName())
algoWireDes.SetName("Ware descritisation")
hypNbSeg = algoWireDes.NumberOfSegments(numberOfSegment)
- print hypNbSeg.GetName()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "Nb. Segments")
algoMef = mesh.Triangle()
listHyp = algoMef.GetCompatibleHypothesis()
- print algoMef.GetName()
+ print(algoMef.GetName())
algoMef.SetName("Triangle (Mefisto)")
hypArea200 = algoMef.MaxElementArea(maxElementArea)
- print hypArea200.GetName()
- print hypArea200.GetMaxElementArea()
+ print(hypArea200.GetName())
+ print(hypArea200.GetMaxElementArea())
smesh.SetName(hypArea200, "Max. Element Area")
- print "---------------------Compute the mesh"
+ print("---------------------Compute the mesh")
ret = mesh.Compute()
- print ret
+ print(ret)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import math
pass
pass
if len(nfaces)!=nbf:
- print "len(nfaces)!=nbf"
+ print("len(nfaces)!=nbf")
break
newfaces.append(nfaces)
# update faces for before next step of extrusion
oldnodes = newnodes
pass
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
anElemType = SMESH.FACE;
- print "anElemType =", anElemType
+ print("anElemType =", anElemType)
#anIds = CheckBelongToGeomFilter(mesh,box,subShapeList[1],anElemType)
anIds = CheckBelongToGeomFilter(mesh,box,box,anElemType)
- print "Number of ids = ", len(anIds)
- print "anIds = ", anIds
+ print("Number of ids = ", len(anIds))
+ print("anIds = ", anIds)
## Check old version
#anIds = CheckBelongToGeomFilterOld(smesh,mesh.GetMesh(),box,box,anElemType)
#print "anIds = ", anIds
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
aSmeshGroup1 = mesh.GroupOnGeom(aGeomGroup1, "SMESHGroup1", SMESH.FACE)
aSmeshGroup2 = mesh.GroupOnGeom(aGeomGroup2, "SMESHGroup2", SMESH.EDGE)
- print "Create aGroupOnShell - a group linked to a shell"
+ print("Create aGroupOnShell - a group linked to a shell")
aGroupOnShell = mesh.GroupOnGeom(shell, "GroupOnShell", SMESH.EDGE)
- print "aGroupOnShell type =", aGroupOnShell.GetType()
- print "aGroupOnShell size =", aGroupOnShell.Size()
- print "aGroupOnShell ids :", aGroupOnShell.GetListOfID()
+ print("aGroupOnShell type =", aGroupOnShell.GetType())
+ print("aGroupOnShell size =", aGroupOnShell.Size())
+ print("aGroupOnShell ids :", aGroupOnShell.GetListOfID())
- print " "
+ print(" ")
- print "Modify <LocalLength> hypothesis: 100 -> 50"
+ print("Modify <LocalLength> hypothesis: 100 -> 50")
hypLen1.SetLength(50)
- print "Contents of aGroupOnShell changes:"
- print "aGroupOnShell size =", aGroupOnShell.Size()
- print "aGroupOnShell ids :", aGroupOnShell.GetListOfID()
+ print("Contents of aGroupOnShell changes:")
+ print("aGroupOnShell size =", aGroupOnShell.Size())
+ print("aGroupOnShell ids :", aGroupOnShell.GetListOfID())
- print " "
+ print(" ")
- print "Re-compute mesh, contents of aGroupOnShell changes again:"
+ print("Re-compute mesh, contents of aGroupOnShell changes again:")
mesh.Compute()
- print "aGroupOnShell size =", aGroupOnShell.Size()
- print "aGroupOnShell ids :", aGroupOnShell.GetListOfID()
+ print("aGroupOnShell size =", aGroupOnShell.Size())
+ print("aGroupOnShell ids :", aGroupOnShell.GetListOfID())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import os
import math
#Sketcher_1 creation
- print "Sketcher creation..."
+ print("Sketcher creation...")
Sketcher_1 = geompy.MakeSketcher("Sketcher:F 100 -57.7:TT 100 57.7:TT 0 115.47:TT -100 57.7:TT -100 -57.7:TT 0 -115.47:WW")
geompy.addToStudy(Sketcher_1, "Sketcher_1")
Face_1 = geompy.MakeFace(Sketcher_1, 1)
geompy.addToStudy(Face_1, "Face_1")
#Line creation
- print "Line creation..."
+ print("Line creation...")
Line_1 = geompy.MakeLineTwoPnt(geompy.MakeVertex(0,0,0), geompy.MakeVertex(0,0,100))
geompy.addToStudy(Line_1, "Line_1")
#Prism creation
- print "Prism creation..."
+ print("Prism creation...")
Prism_1 = geompy.MakePrismVecH(Face_1, Line_1, 100)
geompy.addToStudy(Prism_1, "Prism_1")
#Sketcher_2 creation
- print "Sketcher creation..."
+ print("Sketcher creation...")
Sketcher_2 = geompy.MakeSketcher("Sketcher:F 50 0:TT 80 0:TT 112 13:TT 112 48:TT 80 63:TT 80 90:TT 50 90:WW", [0,0,0, 1,0,0, 0,1,0])
geompy.addToStudy(Sketcher_2, "Sketcher_2")
Face_2 = geompy.MakeFace(Sketcher_2, 1)
geompy.addToStudy(Face_2, "Face_2")
#Revolution creation
- print "Revolution creation..."
+ print("Revolution creation...")
Revolution_1 = geompy.MakeRevolution(Face_2, Line_1, 2*math.pi)
geompy.addToStudy(Revolution_1, "Revolution_1")
#Common applying
- print "Common of Revolution and Prism..."
+ print("Common of Revolution and Prism...")
Common_1 = geompy.MakeBoolean(Revolution_1, Prism_1, 1)
geompy.addToStudy(Common_1, "Common_1")
geompy.addToStudyInFather(Common_1, CommonExplodedListEdges[i], name)
#Fillet applying
- print "Fillet creation..."
+ print("Fillet creation...")
Fillet_1 = geompy.MakeFillet(Common_1, 10, geompy.ShapeType["EDGE"], [5])
geompy.addToStudy(Fillet_1, "Fillet_1")
#Chamfer applying
- print "Chamfer creation..."
+ print("Chamfer creation...")
cyl_face = geompy.GetFaceNearPoint( Fillet_1, geompy.MakeVertex( 50, 0, 45 ), theName='cyl_face')
cyl_face_id = geompy.GetSubShapeID( Fillet_1, cyl_face )
top_face = geompy.GetFaceNearPoint( Fillet_1, geompy.MakeVertex( 60, 0, 90 ), theName='top_face')
Chamfer_2 = geompy.MakeChamferEdge(Chamfer_1, 10, 10, cyl_face_id, top_face_id, theName='Chamfer_2' )
#Import of the shape from "slots.brep"
- print "Import multi-rotation from the DATA_DIR/Shapes/Brep/slots.brep"
+ print("Import multi-rotation from the DATA_DIR/Shapes/Brep/slots.brep")
thePath = os.getenv("DATA_DIR")
theFileName = os.path.join( thePath,"Shapes","Brep","slots.brep")
theShapeForCut = geompy.ImportBREP(theFileName)
geompy.addToStudy(theShapeForCut, "slot.brep_1")
#Cut applying
- print "Cut..."
+ print("Cut...")
Cut_1 = geompy.MakeBoolean(Chamfer_2, theShapeForCut, 2)
Cut_1_ID = geompy.addToStudy(Cut_1, "Cut_1")
mesh = smesh.Mesh(shape_mesh, "Nut")
#HYPOTHESIS CREATION
- print "-------------------------- Average length"
+ print("-------------------------- Average length")
theAverageLength = 5
algoReg1D = mesh.Segment()
hAvLength = algoReg1D.LocalLength(theAverageLength)
- print hAvLength.GetName()
- print hAvLength.GetId()
- print hAvLength.GetLength()
+ print(hAvLength.GetName())
+ print(hAvLength.GetId())
+ print(hAvLength.GetLength())
smesh.SetName(hAvLength, "AverageLength_"+str(theAverageLength))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
theMaxElementArea = 20
algoMef = mesh.Triangle(smeshBuilder.MEFISTO)
hArea = algoMef.MaxElementArea( theMaxElementArea )
- print hArea.GetName()
- print hArea.GetId()
- print hArea.GetMaxElementArea()
+ print(hArea.GetName())
+ print(hArea.GetId())
+ print(hArea.GetMaxElementArea())
smesh.SetName(hArea, "MaxElementArea_"+str(theMaxElementArea))
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
theMaxElementVolume = 150
algoNg = mesh.Tetrahedron(smeshBuilder.NETGEN)
hVolume = algoNg.MaxElementVolume( theMaxElementVolume )
- print hVolume.GetName()
- print hVolume.GetId()
- print hVolume.GetMaxElementVolume()
+ print(hVolume.GetName())
+ print(hVolume.GetId())
+ print(hVolume.GetMaxElementVolume())
smesh.SetName(hVolume, "MaxElementVolume_"+str(theMaxElementVolume))
- print "-------------------------- compute the mesh of the mechanic piece"
+ print("-------------------------- compute the mesh of the mechanic piece")
mesh.Compute()
- print "Information about the Nut:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print("Information about the Nut:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
from math import sqrt
barier_height = 7.0
barier_radius = 5.6 / 2 # Rayon de la bariere
colis_radius = 1.0 / 2 # Rayon du colis
-colis_step = 2.0 # Distance s\89parant deux colis
+colis_step = 2.0 # Distance s�parant deux colis
cc_width = 0.11 # Epaisseur du complement de colisage
# --
SubShape_theShape = geompy.SubShapeAll(Compound1,geompy.ShapeType["SOLID"])
alveole = geompy.MakePartition(SubShape_theShape)
- print "Analysis of the geometry to mesh (right after the Partition) :"
+ print("Analysis of the geometry to mesh (right after the Partition) :")
subShellList = geompy.SubShapeAll(alveole, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(alveole, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(alveole, geompy.ShapeType["EDGE"])
- print "number of Shells in alveole : ", len(subShellList)
- print "number of Faces in alveole : ", len(subFaceList)
- print "number of Edges in alveole : ", len(subEdgeList)
+ print("number of Shells in alveole : ", len(subShellList))
+ print("number of Faces in alveole : ", len(subFaceList))
+ print("number of Edges in alveole : ", len(subEdgeList))
subshapes = geompy.SubShapeAll(alveole, geompy.ShapeType["SHAPE"])
idalveole = geompy.addToStudy(alveole, "alveole")
- print "Analysis of the geometry to mesh (right after the MakeCompound) :"
+ print("Analysis of the geometry to mesh (right after the MakeCompound) :")
subShellList = geompy.SubShapeAll(alveole, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(alveole, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(alveole, geompy.ShapeType["EDGE"])
- print "number of Shells in alveole : ", len(subShellList)
- print "number of Faces in alveole : ", len(subFaceList)
- print "number of Edges in alveole : ", len(subEdgeList)
+ print("number of Shells in alveole : ", len(subShellList))
+ print("number of Faces in alveole : ", len(subFaceList))
+ print("number of Edges in alveole : ", len(subEdgeList))
status = geompy.CheckShape(alveole)
- print " check status ", status
+ print(" check status ", status)
# ---- init a Mesh with the alveole
mesh = smesh.Mesh(shape_mesh, "MeshAlveole")
- print "-------------------------- create Hypothesis (In this case global hypothesis are used)"
+ print("-------------------------- create Hypothesis (In this case global hypothesis are used)")
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 10
regular1D = mesh.Segment()
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 0.1
mefisto2D = mesh.Triangle()
hypArea = mefisto2D.MaxElementArea(maxElementArea)
- print hypArea.GetName()
- print hypArea.GetId()
- print hypArea.GetMaxElementArea()
+ print(hypArea.GetName())
+ print(hypArea.GetId())
+ print(hypArea.GetMaxElementArea())
smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
maxElementVolume = 0.5
netgen3D = mesh.Tetrahedron(smeshBuilder.NETGEN)
hypVolume = netgen3D.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "MaxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute the mesh of alveole "
+ print("-------------------------- compute the mesh of alveole ")
ret = mesh.Compute()
if ret != 0:
log=mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the Mesh_mechanic:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print(linelog)
+ print("Information about the Mesh_mechanic:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
else:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define 2 boxes box1 and box2
idbox1 = geompy.addToStudy(box1, "box1")
- print "Analysis of the geometry box1 :"
+ print("Analysis of the geometry box1 :")
subShellList = geompy.SubShapeAll(box1, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box1, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box1, geompy.ShapeType["EDGE"])
- print "number of Shells in box1 : ", len(subShellList)
- print "number of Faces in box1 : ", len(subFaceList)
- print "number of Edges in box1 : ", len(subEdgeList)
+ print("number of Shells in box1 : ", len(subShellList))
+ print("number of Faces in box1 : ", len(subFaceList))
+ print("number of Edges in box1 : ", len(subEdgeList))
box2 = geompy.MakeBox(100., 0., 0., 200., 200., 300.)
idbox2 = geompy.addToStudy(box2, "box2")
- print "Analysis of the geometry box2 :"
+ print("Analysis of the geometry box2 :")
subShellList = geompy.SubShapeAll(box2, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box2, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box2, geompy.ShapeType["EDGE"])
- print "number of Shells in box2 : ", len(subShellList)
- print "number of Faces in box2 : ", len(subFaceList)
- print "number of Edges in box2 : ", len(subEdgeList)
+ print("number of Shells in box2 : ", len(subShellList))
+ print("number of Faces in box2 : ", len(subFaceList))
+ print("number of Edges in box2 : ", len(subEdgeList))
# append the tow boxes to make ine shel, referrencing only once
# the internal interface
shell = geompy.MakePartition([box1, box2])
idshell = geompy.addToStudy(shell, "shell")
- print "Analysis of the geometry shell (union of box1 and box2) :"
+ print("Analysis of the geometry shell (union of box1 and box2) :")
subShellList = geompy.SubShapeAll(shell, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(shell, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(shell, geompy.ShapeType["EDGE"])
- print "number of Shells in shell : ", len(subShellList)
- print "number of Faces in shell : ", len(subFaceList)
- print "number of Edges in shell : ", len(subEdgeList)
+ print("number of Shells in shell : ", len(subShellList))
+ print("number of Faces in shell : ", len(subFaceList))
+ print("number of Edges in shell : ", len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
# ---- set Hypothesis and Algorithm
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 10
regular1D = mesh.Segment()
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 500
mefisto2D = mesh.Triangle()
hypArea = mefisto2D.MaxElementArea(maxElementArea)
- print hypArea.GetName()
- print hypArea.GetId()
- print hypArea.GetMaxElementArea()
+ print(hypArea.GetName())
+ print(hypArea.GetId())
+ print(hypArea.GetMaxElementArea())
smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
maxElementVolume = 500
netgen3D = mesh.Tetrahedron(smeshBuilder.NETGEN)
hypVolume = netgen3D.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "MaxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute shell"
+ print("-------------------------- compute shell")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the MeshBox2:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print(linelog)
+ print("Information about the MeshBox2:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
else:
- print "probleme when computing the mesh"
+ print("probleme when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define 3 boxes box1, box2 and box3
idbox1 = geompy.addToStudy(box1, "box1")
- print "Analysis of the geometry box1 :"
+ print("Analysis of the geometry box1 :")
subShellList = geompy.SubShapeAll(box1, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box1, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box1, geompy.ShapeType["EDGE"])
- print "number of Shells in box1 : ", len(subShellList)
- print "number of Faces in box1 : ", len(subFaceList)
- print "number of Edges in box1 : ", len(subEdgeList)
+ print("number of Shells in box1 : ", len(subShellList))
+ print("number of Faces in box1 : ", len(subFaceList))
+ print("number of Edges in box1 : ", len(subEdgeList))
box2 = geompy.MakeBox(100., 0., 0., 200., 200., 300.)
idbox2 = geompy.addToStudy(box2, "box2")
- print "Analysis of the geometry box2 :"
+ print("Analysis of the geometry box2 :")
subShellList = geompy.SubShapeAll(box2, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box2, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box2, geompy.ShapeType["EDGE"])
- print "number of Shells in box2 : ", len(subShellList)
- print "number of Faces in box2 : ", len(subFaceList)
- print "number of Edges in box2 : ", len(subEdgeList)
+ print("number of Shells in box2 : ", len(subShellList))
+ print("number of Faces in box2 : ", len(subFaceList))
+ print("number of Edges in box2 : ", len(subEdgeList))
box3 = geompy.MakeBox(0., 0., 300., 200., 200., 500.)
idbox3 = geompy.addToStudy(box3, "box3")
- print "Analysis of the geometry box3 :"
+ print("Analysis of the geometry box3 :")
subShellList = geompy.SubShapeAll(box3, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box3, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box3, geompy.ShapeType["EDGE"])
- print "number of Shells in box3 : ", len(subShellList)
- print "number of Faces in box3 : ", len(subFaceList)
- print "number of Edges in box3 : ", len(subEdgeList)
+ print("number of Shells in box3 : ", len(subShellList))
+ print("number of Faces in box3 : ", len(subFaceList))
+ print("number of Edges in box3 : ", len(subEdgeList))
shell = geompy.MakePartition([box1, box2, box3])
idshell = geompy.addToStudy(shell,"shell")
- print "Analysis of the geometry shell (union of box1, box2 and box3) :"
+ print("Analysis of the geometry shell (union of box1, box2 and box3) :")
subShellList = geompy.SubShapeAll(shell, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(shell, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(shell, geompy.ShapeType["EDGE"])
- print "number of Shells in shell : ", len(subShellList)
- print "number of Faces in shell : ", len(subFaceList)
- print "number of Edges in shell : ", len(subEdgeList)
+ print("number of Shells in shell : ", len(subShellList))
+ print("number of Faces in shell : ", len(subFaceList))
+ print("number of Edges in shell : ", len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
# ---- set Hypothesis and Algorithm
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 10
regular1D = mesh.Segment()
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 500
mefisto2D = mesh.Triangle()
hypArea = mefisto2D.MaxElementArea(maxElementArea)
- print hypArea.GetName()
- print hypArea.GetId()
- print hypArea.GetMaxElementArea()
+ print(hypArea.GetName())
+ print(hypArea.GetId())
+ print(hypArea.GetMaxElementArea())
smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
maxElementVolume = 500
netgen3D = mesh.Tetrahedron(smeshBuilder.NETGEN)
hypVolume = netgen3D.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "MaxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute shell"
+ print("-------------------------- compute shell")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the MeshBox3:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print(linelog)
+ print("Information about the MeshBox3:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
else:
- print "probleme when computing the mesh"
+ print("probleme when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define a boxe
idbox = geompy.addToStudy(box, "box")
- print "Analysis of the geometry box :"
+ print("Analysis of the geometry box :")
subShellList = geompy.SubShapeAll(box, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(box, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(box, geompy.ShapeType["EDGE"])
- print "number of Shells in box : ", len(subShellList)
- print "number of Faces in box : ", len(subFaceList)
- print "number of Edges in box : ", len(subEdgeList)
+ print("number of Shells in box : ", len(subShellList))
+ print("number of Faces in box : ", len(subFaceList))
+ print("number of Edges in box : ", len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
# ---- set Hypothesis and Algorithm
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 10
regular1D = mesh.Segment()
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 500
mefisto2D = mesh.Triangle()
hypArea = mefisto2D.MaxElementArea(maxElementArea)
- print hypArea.GetName()
- print hypArea.GetId()
- print hypArea.GetMaxElementArea()
+ print(hypArea.GetName())
+ print(hypArea.GetId())
+ print(hypArea.GetMaxElementArea())
smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
maxElementVolume = 500
netgen3D = mesh.Tetrahedron(smeshBuilder.NETGEN)
hypVolume = netgen3D.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "MaxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute the mesh of the boxe"
+ print("-------------------------- compute the mesh of the boxe")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the MeshBox:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print(linelog)
+ print("Information about the MeshBox:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
else:
- print "probleme when computing the mesh"
+ print("probleme when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
mesh = SMESH_mechanic.mesh
# ---- Criterion : AREA > 100
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Area > 100 Nb = ", len( anIds )
+ print("Criterion: Area > 100 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Taper > 3e-15 Nb = ", len( anIds )
+ print("Criterion: Taper > 3e-15 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Aspect Ratio > 1.3 Nb = ", len( anIds )
+ print("Criterion: Aspect Ratio > 1.3 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Minimum Angle < 30 Nb = ", len( anIds )
+ print("Criterion: Minimum Angle < 30 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Warp > 2e-13 Nb = ", len( anIds )
+ print("Criterion: Warp > 2e-13 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Skew > 18 Nb = ", len( anIds )
+ print("Criterion: Skew > 18 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Length > 10 Nb = ", len( anIds )
+ print("Criterion: Length > 10 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Borders at multi-connections = 2 Nb = ", len( anIds )
+ print("Criterion: Borders at multi-connections = 2 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
# print result
anIds = aGroup.GetIDs()
- print "Criterion: Element Diameter 2D > 10 Nb = ", len( anIds )
+ print("Criterion: Element Diameter 2D > 10 Nb = ", len( anIds ))
#for i in range( len( anIds ) ):
#print anIds[ i ]
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import math
vol = geompy.MakeGlueFaces(volComp,tol3d)
idVol = geompy.addToStudy(vol,"volume")
- print "Analysis of the final volume:"
+ print("Analysis of the final volume:")
subShellList = geompy.SubShapeAllSorted(vol,ShapeTypeShell)
subFaceList = geompy.SubShapeAllSorted(vol,ShapeTypeFace)
subEdgeList = geompy.SubShapeAllSorted(vol,ShapeTypeEdge)
- print "number of Shells in the volume : ",len(subShellList)
- print "number of Faces in the volume : ",len(subFaceList)
- print "number of Edges in the volume : ",len(subEdgeList)
+ print("number of Shells in the volume : ",len(subShellList))
+ print("number of Faces in the volume : ",len(subFaceList))
+ print("number of Edges in the volume : ",len(subEdgeList))
idSubEdge = []
for k in range(len(subEdgeList)):
idEdgeZ.append(geompy.addToStudyInFather(vol,edgeZ[i],"EdgeZ"+str(i+1)))
### ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# ---- init a Mesh with the volume
# ---- set Hypothesis and Algorithm to main shape
- print "-------------------------- NumberOfSegments the global one"
+ print("-------------------------- NumberOfSegments the global one")
numberOfSegments = 10
regular1D = mesh.Segment()
regular1D.SetName("Wire Discretisation")
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments")
- print "-------------------------- Quadrangle_2D"
+ print("-------------------------- Quadrangle_2D")
quad2D=mesh.Quadrangle()
quad2D.SetName("Quadrangle_2D")
- print "-------------------------- Hexa_3D"
+ print("-------------------------- Hexa_3D")
hexa3D=mesh.Hexahedron()
hexa3D.SetName("Hexa_3D")
- print "-------------------------- NumberOfSegments in the Z direction"
+ print("-------------------------- NumberOfSegments in the Z direction")
numberOfSegmentsZ = 40
for i in range(8):
- print "-------------------------- add hypothesis to edge in the Z directions", (i+1)
+ print("-------------------------- add hypothesis to edge in the Z directions", (i+1))
algo = mesh.Segment(edgeZ[i])
hyp = algo.NumberOfSegments(numberOfSegmentsZ)
smesh.SetName(algo.GetSubMesh(), "SubMeshEdgeZ_"+str(i+1))
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
- print "-------------------------- compute the mesh of the volume"
+ print("-------------------------- compute the mesh of the volume")
ret=mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
## log=mesh.GetLog(0) # no erase trace
## for linelog in log:
## print linelog
- print "Information about the MeshBox :"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print("Information about the MeshBox :")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
else:
- print "problem when Computing the mesh"
+ print("problem when Computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
compshell = SMESH_fixation.compshell
idcomp = SMESH_fixation.idcomp
geompy = SMESH_fixation.geompy
salome = SMESH_fixation.salome
- print "Analysis of the geometry to be meshed :"
+ print("Analysis of the geometry to be meshed :")
subShellList = geompy.SubShapeAll(compshell, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(compshell, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(compshell, geompy.ShapeType["EDGE"])
- print "number of Shells in compshell : ", len(subShellList)
- print "number of Faces in compshell : ", len(subFaceList)
- print "number of Edges in compshell : ", len(subEdgeList)
+ print("number of Shells in compshell : ", len(subShellList))
+ print("number of Faces in compshell : ", len(subFaceList))
+ print("number of Edges in compshell : ", len(subEdgeList))
status = geompy.CheckShape(compshell)
- print " check status ", status
+ print(" check status ", status)
### ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# ---- init a Mesh with the compshell
shape_mesh = salome.IDToObject( idcomp )
# ---- set Hypothesis and Algorithm
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 5
regular1D = mesh.Segment()
regular1D.SetName("Wire Discretisation")
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
- print "-------------------------- Quadrangle_2D"
+ print("-------------------------- Quadrangle_2D")
quad2D = mesh.Quadrangle()
quad2D.SetName("Quadrangle_2D")
- print "-------------------------- Hexa_3D"
+ print("-------------------------- Hexa_3D")
hexa3D = mesh.Hexahedron()
hexa3D.SetName("Hexa_3D")
- print "-------------------------- compute compshell"
+ print("-------------------------- compute compshell")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the MeshcompShel:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of hexahedrons : ", mesh.NbHexas()
+ print(linelog)
+ print("Information about the MeshcompShel:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of hexahedrons : ", mesh.NbHexas())
else:
- print "problem when Computing the mesh"
+ print("problem when Computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
compshell = SMESH_fixation.compshell
idcomp = SMESH_fixation.idcomp
geompy = SMESH_fixation.geompy
salome = SMESH_fixation.salome
- print "Analysis of the geometry to be meshed :"
+ print("Analysis of the geometry to be meshed :")
subShellList = geompy.SubShapeAll(compshell, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(compshell, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(compshell, geompy.ShapeType["EDGE"])
- print "number of Shells in compshell : ", len(subShellList)
- print "number of Faces in compshell : ", len(subFaceList)
- print "number of Edges in compshell : ", len(subEdgeList)
+ print("number of Shells in compshell : ", len(subShellList))
+ print("number of Faces in compshell : ", len(subFaceList))
+ print("number of Edges in compshell : ", len(subEdgeList))
status = geompy.CheckShape(compshell)
- print " check status ", status
+ print(" check status ", status)
### ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
- print "-------------------------- create Mesh, algorithm, hypothesis"
+ print("-------------------------- create Mesh, algorithm, hypothesis")
mesh = smesh.Mesh(compshell, "MeshcompShel");
netgen = mesh.Tetrahedron(smeshBuilder.FULL_NETGEN)
netgen.SetFineness( smeshBuilder.Fine )
#netgen.SetOptimize( 1 )
- print "-------------------------- compute mesh"
+ print("-------------------------- compute mesh")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
- print "Information about the MeshcompShel:"
- print "Number of nodes : ", mesh.GetMesh().NbNodes()
- print "Number of edges : ", mesh.GetMesh().NbEdges()
- print "Number of faces : ", mesh.GetMesh().NbFaces()
- print "Number of triangles : ", mesh.GetMesh().NbTriangles()
- print "Number of volumes : ", mesh.GetMesh().NbVolumes()
- print "Number of tetrahedrons : ", mesh.GetMesh().NbTetras()
+ print("Information about the MeshcompShel:")
+ print("Number of nodes : ", mesh.GetMesh().NbNodes())
+ print("Number of edges : ", mesh.GetMesh().NbEdges())
+ print("Number of faces : ", mesh.GetMesh().NbFaces())
+ print("Number of triangles : ", mesh.GetMesh().NbTriangles())
+ print("Number of volumes : ", mesh.GetMesh().NbVolumes())
+ print("Number of tetrahedrons : ", mesh.GetMesh().NbTetras())
else:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
compshell = SMESH_fixation.compshell
idcomp = SMESH_fixation.idcomp
geompy = SMESH_fixation.geompy
salome = SMESH_fixation.salome
- print "Analysis of the geometry to be meshed :"
+ print("Analysis of the geometry to be meshed :")
subShellList = geompy.SubShapeAll(compshell, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(compshell, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(compshell, geompy.ShapeType["EDGE"])
- print "number of Shells in compshell : ", len(subShellList)
- print "number of Faces in compshell : ", len(subFaceList)
- print "number of Edges in compshell : ", len(subEdgeList)
+ print("number of Shells in compshell : ", len(subShellList))
+ print("number of Faces in compshell : ", len(subFaceList))
+ print("number of Edges in compshell : ", len(subEdgeList))
status = geompy.CheckShape(compshell)
- print " check status ", status
+ print(" check status ", status)
### ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# ---- init a Mesh with the compshell
# ---- set Hypothesis and Algorithm
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegments = 5
regular1D = mesh.Segment()
regular1D.SetName("Wire Discretisation")
hypNbSeg = regular1D.NumberOfSegments(numberOfSegments)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegments))
## print "-------------------------- MaxElementArea"
## print hypArea.GetMaxElementArea()
## smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
- print "-------------------------- LengthFromEdges"
+ print("-------------------------- LengthFromEdges")
mefisto2D = mesh.Triangle()
mefisto2D.SetName("MEFISTO_2D")
hypLengthFromEdges = mefisto2D.LengthFromEdges()
- print hypLengthFromEdges.GetName()
- print hypLengthFromEdges.GetId()
+ print(hypLengthFromEdges.GetName())
+ print(hypLengthFromEdges.GetId())
smesh.SetName(hypLengthFromEdges, "LengthFromEdges")
- print "-------------------------- MaxElementVolume"
+ print("-------------------------- MaxElementVolume")
maxElementVolume = 1000
netgen3D = mesh.Tetrahedron(smeshBuilder.NETGEN)
netgen3D.SetName("NETGEN_3D")
hypVolume = netgen3D.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "MaxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute compshell"
+ print("-------------------------- compute compshell")
ret = mesh.Compute(mesh)
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the MeshcompShel:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons : ", mesh.NbTetras()
+ print(linelog)
+ print("Information about the MeshcompShel:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons : ", mesh.NbTetras())
else:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---------------------------- GEOM --------------------------------------
shape = geompy.Import(filename, "BREP")
idShape = geompy.addToStudy(shape, "flight")
- print "Analysis of the geometry flight :"
+ print("Analysis of the geometry flight :")
subShellList = geompy.SubShapeAll(shape, geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(shape, geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(shape, geompy.ShapeType["EDGE"])
- print "number of Shells in flight : ", len(subShellList)
- print "number of Faces in flight : ", len(subFaceList)
- print "number of Edges in flight : ", len(subEdgeList)
+ print("number of Shells in flight : ", len(subShellList))
+ print("number of Faces in flight : ", len(subFaceList))
+ print("number of Edges in flight : ", len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# ---- init a Mesh with the shell
shape_mesh = salome.IDToObject( idShape )
# ---- set Hypothesis and Algorithm
- print "-------------------------- LocalLength"
+ print("-------------------------- LocalLength")
lengthOfSegments = 0.3
regular1D = mesh.Segment()
hypLength = regular1D.LocalLength(lengthOfSegments)
- print hypLength.GetName()
- print hypLength.GetId()
- print hypLength.GetLength()
+ print(hypLength.GetName())
+ print(hypLength.GetId())
+ print(hypLength.GetLength())
smesh.SetName(hypLength, "LocalLength_" + str(lengthOfSegments))
- print "-------------------------- LengthFromEdges"
+ print("-------------------------- LengthFromEdges")
mefisto2D = mesh.Triangle()
hypLengthFromEdge = mefisto2D.LengthFromEdges()
- print hypLengthFromEdge.GetName()
- print hypLengthFromEdge.GetId()
+ print(hypLengthFromEdge.GetName())
+ print(hypLengthFromEdge.GetId())
smesh.SetName(hypLengthFromEdge,"LengthFromEdge")
- print "-------------------------- compute the skin flight"
+ print("-------------------------- compute the skin flight")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
log = mesh.GetLog(0) # no erase trace
for linelog in log:
- print linelog
- print "Information about the Mesh_mechanic_tetra:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of volumes : ", mesh.NbVolumes()
+ print(linelog)
+ print("Information about the Mesh_mechanic_tetra:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of volumes : ", mesh.NbVolumes())
else:
- print "probleme when computing the mesh"
+ print("probleme when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# Create box without one plane
aBox = salome.IDToObject( idbox )
# Create mesh
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
mesh = smesh.Mesh(aBox, "Mesh_freebord")
anIds = aGroup.GetIDs()
# print result
- print "Criterion: Free edges Nb = ", len( anIds )
+ print("Criterion: Free edges Nb = ", len( anIds ))
for i in range( len( anIds ) ):
- print anIds[ i ]
+ print(anIds[ i ])
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# -----------------------------------------------------------------------------
edgeGroups = geompy.Propagate( blob )
assert len( edgeGroups ) == 3
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
# -----------------------------------------------------------------------------
- print "-------------------------- mesh"
+ print("-------------------------- mesh")
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# ---- define a mesh on the geom shape 'blob'
mesh=smesh.Mesh(blob, "MeshBlob")
# ---- assign global hypothesis and algorithms to mesh
- print "-------------------------- add hypothesis to mesh"
+ print("-------------------------- add hypothesis to mesh")
algo1 = mesh.Segment()
algo2 = mesh.Quadrangle()
algo3 = mesh.Hexahedron()
pass
# ---- compute mesh
- print "-------------------------- compute mesh"
+ print("-------------------------- compute mesh")
ok = mesh.Compute()
if ok:
- print "Information about the Mesh:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of hexahedrons : ", mesh.NbHexas()
+ print("Information about the Mesh:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of hexahedrons : ", mesh.NbHexas())
else:
- print "problem when Computing the mesh"
+ print("problem when Computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
from salome.StdMeshers import StdMeshersBuilder
Id_SubFace4 = geompy.addToStudyInFather( mechanic, sub_face4, name )
# ---------------------------- SMESH --------------------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
# -- Init --
shape_mesh = salome.IDToObject( Id_mechanic )
mesh = smesh.Mesh(shape_mesh, "Mesh_mechanic")
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegment = 10
algo = mesh.Segment()
hypNbSeg = algo.NumberOfSegments(numberOfSegment)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_10")
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 25
algo = mesh.Triangle()
hypArea25 = algo.MaxElementArea(maxElementArea)
- print hypArea25.GetName()
- print hypArea25.GetId()
- print hypArea25.GetMaxElementArea()
+ print(hypArea25.GetName())
+ print(hypArea25.GetId())
+ print(hypArea25.GetMaxElementArea())
smesh.SetName(hypArea25, "MaxElementArea_25")
# Create submesh on sub_face1 - sub_face4
algo = mesh.Quadrangle(sub_face4)
smesh.SetName(algo.GetSubMesh(), "SubMeshFace4")
- print "-------------------------- compute the mesh of the mechanic piece"
+ print("-------------------------- compute the mesh of the mechanic piece")
mesh.Compute()
- print "Information about the Mesh_mechanic:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print("Information about the Mesh_mechanic:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---------------------------- GEOM --------------------------------------
mesh = smesh.Mesh(shape_mesh, "Mesh_mechanic")
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
numberOfSegment = 10
algo = mesh.Segment()
hypNbSeg = algo.NumberOfSegments(numberOfSegment)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegment))
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
maxElementArea = 25
algo = mesh.Triangle()
hypArea25 = algo.MaxElementArea(maxElementArea)
- print hypArea25.GetName()
- print hypArea25.GetId()
- print hypArea25.GetMaxElementArea()
+ print(hypArea25.GetName())
+ print(hypArea25.GetId())
+ print(hypArea25.GetMaxElementArea())
smesh.SetName(hypArea25, "MaxElementArea_" + str(maxElementArea))
submesh4 = algo.GetSubMesh()
- print "-------------------------- compute the mesh of the mechanic piece"
+ print("-------------------------- compute the mesh of the mechanic piece")
mesh.Compute()
- print "Information about the Mesh_mechanic:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print("Information about the Mesh_mechanic:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
#1 cutting of quadrangles of the 'SubMeshFace2' submesh
#9 reorientation of the submesh1
mesh.ReorientObject(submesh1)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---------------------------- GEOM --------------------------------------
# ---- Analysis of the geometry
- print "Analysis of the geometry mechanic :"
+ print("Analysis of the geometry mechanic :")
subShellList = geompy.SubShapeAll(mechanic,geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(mechanic,geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(mechanic,geompy.ShapeType["EDGE"])
- print "number of Shells in mechanic : ",len(subShellList)
- print "number of Faces in mechanic : ",len(subFaceList)
- print "number of Edges in mechanic : ",len(subEdgeList)
+ print("number of Shells in mechanic : ",len(subShellList))
+ print("number of Faces in mechanic : ",len(subFaceList))
+ print("number of Edges in mechanic : ",len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
- print "-------------------------- create Mesh, algorithm, hypothesis"
+ print("-------------------------- create Mesh, algorithm, hypothesis")
mesh = smesh.Mesh(mechanic, "Mesh_mechanic");
netgen = mesh.Triangle(smeshBuilder.NETGEN)
netgen.SetQuadAllowed( 1 )
#netgen.SetOptimize( 1 )
- print "-------------------------- compute mesh"
+ print("-------------------------- compute mesh")
ret = mesh.Compute()
- print ret
+ print(ret)
if ret != 0:
- print "Information about the MeshcompShel:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of quadrangles : ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons : ", mesh.NbTetras()
+ print("Information about the MeshcompShel:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of quadrangles : ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons : ", mesh.NbTetras())
else:
- print "problem when computing the mesh"
+ print("problem when computing the mesh")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---------------------------- GEOM --------------------------------------
# ---- Analysis of the geometry
- print "Analysis of the geometry mechanic :"
+ print("Analysis of the geometry mechanic :")
subShellList = geompy.SubShapeAll(mechanic,geompy.ShapeType["SHELL"])
subFaceList = geompy.SubShapeAll(mechanic,geompy.ShapeType["FACE"])
subEdgeList = geompy.SubShapeAll(mechanic,geompy.ShapeType["EDGE"])
- print "number of Shells in mechanic : ",len(subShellList)
- print "number of Faces in mechanic : ",len(subFaceList)
- print "number of Edges in mechanic : ",len(subEdgeList)
+ print("number of Shells in mechanic : ",len(subShellList))
+ print("number of Faces in mechanic : ",len(subFaceList))
+ print("number of Edges in mechanic : ",len(subEdgeList))
### ---------------------------- SMESH --------------------------------------
mesh = smesh.Mesh(shape_mesh, "Mesh_mechanic_tetra")
- print "-------------------------- add hypothesis to main mechanic"
+ print("-------------------------- add hypothesis to main mechanic")
numberOfSegment = 10
algo1 = mesh.Segment()
hypNbSeg = algo1.NumberOfSegments(numberOfSegment)
- print hypNbSeg.GetName()
- print hypNbSeg.GetId()
- print hypNbSeg.GetNumberOfSegments()
+ print(hypNbSeg.GetName())
+ print(hypNbSeg.GetId())
+ print(hypNbSeg.GetNumberOfSegments())
smesh.SetName(hypNbSeg, "NumberOfSegments_" + str(numberOfSegment))
algo2 = mesh.Triangle(smeshBuilder.MEFISTO)
hypArea = algo2.MaxElementArea(maxElementArea)
- print hypArea.GetName()
- print hypArea.GetId()
- print hypArea.GetMaxElementArea()
+ print(hypArea.GetName())
+ print(hypArea.GetId())
+ print(hypArea.GetMaxElementArea())
smesh.SetName(hypArea, "MaxElementArea_" + str(maxElementArea))
algo3 = mesh.Tetrahedron(smeshBuilder.NETGEN)
hypVolume = algo3.MaxElementVolume(maxElementVolume)
- print hypVolume.GetName()
- print hypVolume.GetId()
- print hypVolume.GetMaxElementVolume()
+ print(hypVolume.GetName())
+ print(hypVolume.GetId())
+ print(hypVolume.GetMaxElementVolume())
smesh.SetName(hypVolume, "maxElementVolume_" + str(maxElementVolume))
- print "-------------------------- compute the mesh of the mechanic piece"
+ print("-------------------------- compute the mesh of the mechanic piece")
mesh.Compute()
- print "Information about the Mesh_mechanic_tetra:"
- print "Number of nodes : ", mesh.NbNodes()
- print "Number of edges : ", mesh.NbEdges()
- print "Number of faces : ", mesh.NbFaces()
- print "Number of triangles : ", mesh.NbTriangles()
- print "Number of quadrangles: ", mesh.NbQuadrangles()
- print "Number of volumes : ", mesh.NbVolumes()
- print "Number of tetrahedrons: ", mesh.NbTetras()
+ print("Information about the Mesh_mechanic_tetra:")
+ print("Number of nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles : ", mesh.NbTriangles())
+ print("Number of quadrangles: ", mesh.NbQuadrangles())
+ print("Number of volumes : ", mesh.NbVolumes())
+ print("Number of tetrahedrons: ", mesh.NbTetras())
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
from salome.StdMeshers import StdMeshersBuilder
# ---- define a box
- print "Define box"
+ print("Define box")
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
idbox = geompy.addToStudy(box, "box")
# ---- add faces of box to study
- print "Add faces to study"
+ print("Add faces to study")
idface = []
subShapeList = geompy.SubShapeAll(box, geompy.ShapeType["FACE"])
for f in subShapeList:
name = geompy.SubShapeName(f, box)
- print name
+ print(name)
idface.append( geompy.addToStudyInFather(box, f, name) )
# ---- add edges of box to study
- print "Add edges to study"
+ print("Add edges to study")
idedge = []
subShapeList = geompy.SubShapeAll(box, geompy.ShapeType["EDGE"])
for f in subShapeList:
name = geompy.SubShapeName(f, box)
- print name
+ print(name)
idedge.append( geompy.addToStudyInFather(box, f, name) )
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
# ---- launch SMESH
smeshgui = salome.ImportComponentGUI("SMESH")
-smeshgui.Init(salome.myStudyId)
-smesh.SetCurrentStudy(salome.myStudy)
+smeshgui.Init()
+smesh.UpdateStudy()
# ---- Creating meshes
names = [ "MeshBoxReg", "MeshBoxScale", "MeshBoxTable", "MeshBoxExpr" ]
- print "-------------------------- Create ", names[0], " mesh"
+ print("-------------------------- Create ", names[0], " mesh")
mesh = smesh.Mesh(box, names[0])
algo = mesh.Segment()
hyp = algo.NumberOfSegments(7)
algo = mesh.Triangle()
algo.MaxElementArea(2500)
- print "-------------------------- Create ", names[1], " mesh"
+ print("-------------------------- Create ", names[1], " mesh")
mesh = smesh.Mesh(box, names[1])
algo = mesh.Segment()
hyp = algo.NumberOfSegments(7)
algo = mesh.Triangle()
algo.MaxElementArea(2500)
- print "-------------------------- Create ", names[2], " mesh"
+ print("-------------------------- Create ", names[2], " mesh")
mesh = smesh.Mesh(box,names[2])
algo = mesh.Segment()
hyp = algo.NumberOfSegments(7)
algo = mesh.Triangle()
algo.MaxElementArea(2500)
- print "-------------------------- Create ", names[3], " mesh"
+ print("-------------------------- Create ", names[3], " mesh")
mesh = smesh.Mesh(box, names[3])
algo = mesh.Segment()
hyp = algo.NumberOfSegments(10)
algo.MaxElementArea(2500)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define a box
# ---- SMESH
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
box = salome.IDToObject(idb)
mesh = smesh.Mesh(box, "Meshbox")
- print "-------------------------- add hypothesis to box"
+ print("-------------------------- add hypothesis to box")
algo_1 = mesh.Segment(box)
hyp = algo_1.LocalLength(100)
- print hyp.GetName()
- print hyp.GetId()
- print hyp.GetLength()
+ print(hyp.GetName())
+ print(hyp.GetId())
+ print(hyp.GetLength())
algo_2 = mesh.Triangle(smeshBuilder.MEFISTO, box)
hyp = algo_2.MaxElementArea(5000)
- print hyp.GetName()
- print hyp.GetId()
- print hyp.GetMaxElementArea()
+ print(hyp.GetName())
+ print(hyp.GetId())
+ print(hyp.GetMaxElementArea())
smesh.SetName(algo_2.GetSubMesh(), "SubMeshBox")
- print "-------------------------- add hypothesis to edge"
+ print("-------------------------- add hypothesis to edge")
edge = salome.IDToObject(ide)
algo_3 = mesh.Segment(edge)
hyp = algo_3.LocalLength(100)
- print hyp.GetName()
- print hyp.GetId()
- print hyp.GetLength()
+ print(hyp.GetName())
+ print(hyp.GetId())
+ print(hyp.GetLength())
smesh.SetName(algo_3.GetSubMesh(), "SubMeshEdge")
- print "-------------------------- compute face"
+ print("-------------------------- compute face")
face = salome.IDToObject(idf)
ret = mesh.Compute(face)
- print ret
+ print(ret)
log = mesh.GetLog(0) # 0 - GetLog without ClearLog after, else if 1 - ClearLog after
for a in log:
- print "-------"
+ print("-------")
ii = 0
ir = 0
comType = a.commandType
ir = ir+1
r3 = a.coords[ir]
ir = ir+1
- print "AddNode %i - %g %g %g" % (ind, r1, r2, r3)
+ print("AddNode %i - %g %g %g" % (ind, r1, r2, r3))
elif comType == 1:
for i in range(a.number):
ind = a.indexes[ii]
ii = ii+1
i2 = a.indexes[ii]
ii = ii+1
- print "AddEdge %i - %i %i" % (ind, i1, i2)
+ print("AddEdge %i - %i %i" % (ind, i1, i2))
elif comType == 2:
for i in range(a.number):
ind = a.indexes[ii]
- print ind
+ print(ind)
ii = ii+1
- print ii
+ print(ii)
i1 = a.indexes[ii]
ii = ii+1
i2 = a.indexes[ii]
- print i2
+ print(i2)
ii = ii+1
- print "ii", ii
+ print("ii", ii)
i3 = a.indexes[ii]
- print i3
+ print(i3)
#ii = ii+1
ii = ii+1
- print "AddTriangle %i - %i %i %i" % (ind, i1, i2, i3)
+ print("AddTriangle %i - %i %i %i" % (ind, i1, i2, i3))
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define a box
subShapeList = geompy.SubShapeAll(box, geompy.ShapeType["FACE"])
face = subShapeList[0]
name = geompy.SubShapeName(face, box)
- print name
+ print(name)
idface = geompy.addToStudyInFather(box, face, name)
# ---- add shell from box in study
subShellList = geompy.SubShapeAll(box, geompy.ShapeType["SHELL"])
shell = subShellList[0]
name = geompy.SubShapeName(shell, box)
- print name
+ print(name)
idshell = geompy.addToStudyInFather(box, shell, name)
# ---- add first edge of face in study
edgeList = geompy.SubShapeAll(face, geompy.ShapeType["EDGE"])
edge = edgeList[0]
name = geompy.SubShapeName(edge, face)
- print name
+ print(name)
idedge = geompy.addToStudyInFather(face, edge, name)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define a box
subShapeList = geompy.SubShapeAll(box, geompy.ShapeType["FACE"])
face = subShapeList[0]
name = geompy.SubShapeName(face, box)
- print name
+ print(name)
idface = geompy.addToStudyInFather(box, face, name)
# ---- add shell from box in study
subShellList = geompy.SubShapeAll(box, geompy.ShapeType["SHELL"])
shell = subShellList[0]
name = geompy.SubShapeName(shell, box)
- print name
+ print(name)
idshell = geompy.addToStudyInFather(box, shell, name)
# ---- add first edge of face in study
edgeList = geompy.SubShapeAll(face, geompy.ShapeType["EDGE"])
edge = edgeList[0]
name = geompy.SubShapeName(edge, face)
- print name
+ print(name)
idedge = geompy.addToStudyInFather(face, edge, name)
mesh = smesh.Mesh(box, "Meshbox")
- print "-------------------------- add hypothesis to box"
+ print("-------------------------- add hypothesis to box")
algoReg1 = mesh.Segment()
hypNbSeg1 = algoReg1.NumberOfSegments(7)
- print hypNbSeg1.GetName()
- print hypNbSeg1.GetId()
- print hypNbSeg1.GetNumberOfSegments()
+ print(hypNbSeg1.GetName())
+ print(hypNbSeg1.GetId())
+ print(hypNbSeg1.GetNumberOfSegments())
smesh.SetName(hypNbSeg1, "NumberOfSegments_7")
algoMef1 = mesh.Triangle()
hypArea1 = algoMef1.MaxElementArea(2500)
- print hypArea1.GetName()
- print hypArea1.GetId()
- print hypArea1.GetMaxElementArea()
+ print(hypArea1.GetName())
+ print(hypArea1.GetId())
+ print(hypArea1.GetMaxElementArea())
smesh.SetName(hypArea1, "MaxElementArea_2500")
# ---- add hypothesis to edge
- print "-------------------------- add hypothesis to edge"
+ print("-------------------------- add hypothesis to edge")
edge = salome.IDToObject(idedge)
algoReg2 = mesh.Segment(edge)
hypLen1 = algoReg2.LocalLength(100)
smesh.SetName(algoReg2.GetSubMesh(), "SubMeshEdge")
- print hypLen1.GetName()
- print hypLen1.GetId()
- print hypLen1.GetLength()
+ print(hypLen1.GetName())
+ print(hypLen1.GetId())
+ print(hypLen1.GetLength())
smesh.SetName(hypLen1, "Local_Length_100")
# ---- add hypothesis to face
- print "-------------------------- add hypothesis to face"
+ print("-------------------------- add hypothesis to face")
face = salome.IDToObject(idface)
algoMef2 = mesh.Triangle(face)
hypArea2 = algoMef2.MaxElementArea(500)
smesh.SetName(algoMef2.GetSubMesh(), "SubMeshFace")
- print hypArea2.GetName()
- print hypArea2.GetId()
- print hypArea2.GetMaxElementArea()
+ print(hypArea2.GetName())
+ print(hypArea2.GetId())
+ print(hypArea2.GetMaxElementArea())
smesh.SetName(hypArea2, "MaxElementArea_500")
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- define a box
subShapeList = geompy.SubShapeAll(box, geompy.ShapeType["FACE"])
face = subShapeList[0]
name = geompy.SubShapeName(face, box)
- print name
+ print(name)
idface = geompy.addToStudyInFather(box, face, name)
# ---- add shell from box in study
subShellList = geompy.SubShapeAll(box, geompy.ShapeType["SHELL"])
shell = subShellList[0]
name = geompy.SubShapeName(shell, box)
- print name
+ print(name)
idshell = geompy.addToStudyInFather(box, shell, name)
# ---- add first edge of face in study
edgeList = geompy.SubShapeAll(face, geompy.ShapeType["EDGE"])
edge = edgeList[0]
name = geompy.SubShapeName(edge, face)
- print name
+ print(name)
idedge = geompy.addToStudyInFather(face, edge, name)
mesh = smesh.Mesh(box, "Meshbox")
- print "-------------------------- add hypothesis to box"
+ print("-------------------------- add hypothesis to box")
algoReg1 = mesh.Segment()
hypNbSeg1 = algoReg1.NumberOfSegments(7)
- print hypNbSeg1.GetName()
- print hypNbSeg1.GetId()
- print hypNbSeg1.GetNumberOfSegments()
+ print(hypNbSeg1.GetName())
+ print(hypNbSeg1.GetId())
+ print(hypNbSeg1.GetNumberOfSegments())
smesh.SetName(hypNbSeg1, "NumberOfSegments_7")
algoMef1 = mesh.Triangle()
hypArea1 = algoMef1.MaxElementArea(2500)
- print hypArea1.GetName()
- print hypArea1.GetId()
- print hypArea1.GetMaxElementArea()
+ print(hypArea1.GetName())
+ print(hypArea1.GetId())
+ print(hypArea1.GetMaxElementArea())
smesh.SetName(hypArea1, "MaxElementArea_2500")
# ---- add hypothesis to edge
- print "-------------------------- add hypothesis to edge"
+ print("-------------------------- add hypothesis to edge")
edge = salome.IDToObject(idedge)
algoReg2 = mesh.Segment(edge)
hypLen1 = algoReg2.LocalLength(100)
smesh.SetName(algoReg2.GetSubMesh(), "SubMeshEdge")
- print hypLen1.GetName()
- print hypLen1.GetId()
- print hypLen1.GetLength()
+ print(hypLen1.GetName())
+ print(hypLen1.GetId())
+ print(hypLen1.GetLength())
smesh.SetName(hypLen1, "Local_Length_100")
# ---- add hypothesis to face
- print "-------------------------- add hypothesis to face"
+ print("-------------------------- add hypothesis to face")
face = salome.IDToObject(idface)
algoMef2 = mesh.Triangle(face)
hypArea2 = algoMef2.MaxElementArea(500)
smesh.SetName(algoMef2.GetSubMesh(), "SubMeshFace")
- print hypArea2.GetName()
- print hypArea2.GetId()
- print hypArea2.GetMaxElementArea()
+ print(hypArea2.GetName())
+ print(hypArea2.GetId())
+ print(hypArea2.GetMaxElementArea())
smesh.SetName(hypArea2, "MaxElementArea_500")
mesh.Compute()
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
sg = salome.ImportComponentGUI('SMESH')
- if type(sg) != type(salome.salome_ComponentGUI):
+ if not isinstance(sg, type(salome.salome_ComponentGUI)):
sg.CreateAndDisplayActor('0:1:2:3')
# ---- compute box
- print "-------------------------- compute box"
+ print("-------------------------- compute box")
ret = mesh.Compute()
- print ret
+ print(ret)
log = mesh.GetLog(0); # no erase trace
for linelog in log:
- print linelog
+ print(linelog)
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# ---- GEOM
# ---- SMESH
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
mesh = smesh.Mesh(box, "Meshbox")
# Set 1D algorithm/hypotheses to mesh
faces = submesh.GetElementsByType(SMESH.FACE)
if len(faces) > 1:
- print len(faces), len(faces)/2
+ print(len(faces), len(faces)/2)
group1 = mesh.CreateEmptyGroup(SMESH.FACE,"Group of faces")
group2 = mesh.CreateEmptyGroup(SMESH.FACE,"Another group of faces")
group1.Add(faces[:int(len(faces)/2)])
group2.Add(faces[int(len(faces)/2):])
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import CORBA
import os
def ConvertMED2UNV(thePath,theFile) :
anInitFileName = thePath + theFile
aMeshes,aResult = smesh.CreateMeshesFromMED(anInitFileName)
- print aResult, aMeshes
+ print(aResult, aMeshes)
for iMesh in range(len(aMeshes)) :
aMesh = aMeshes[iMesh]
- print aMesh.GetName(),
+ print(aMesh.GetName(), end=' ')
aFileName = anInitFileName
aFileName = os.path.basename(aFileName)
aMesh.SetName(aFileName)
- print aMesh.GetName()
+ print(aMesh.GetName())
aOutPath = '/tmp/'
aFileName = aOutPath + theFile + "." + str(iMesh) + ".unv"
aMesh.ExportUNV(aFileName)
aMesh = smesh.CreateMeshesFromUNV(aFileName)
- print aMesh.GetName(),
+ print(aMesh.GetName(), end=' ')
os.remove(aFileName)
aFileName = os.path.basename(aFileName)
aMesh.SetName(aFileName)
- print aMesh.GetName()
+ print(aMesh.GetName())
aPath = os.getenv('DATA_DIR') + '/MedFiles/'
aListDir = os.listdir(aPath)
- print aListDir
+ print(aListDir)
for iFile in range(len(aListDir)) :
aFileName = aListDir[iFile]
aName,anExt = os.path.splitext(aFileName)
if anExt == ".med" :
aFileName = os.path.basename(aFileName)
- print aFileName
+ print(aFileName)
ConvertMED2UNV(aPath,aFileName)
#break
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
def LengthNearVertex(self, length, vertex=0, UseExisting=0):
import types
store_geom = self.geom
- if type(vertex) is types.IntType:
+ if isinstance(vertex, int):
if vertex == 0 or vertex == 1:
from salome.geom import geomBuilder
vertex = self.mesh.geompyD.ExtractShapes(self.geom, geomBuilder.geomBuilder.ShapeType["VERTEX"],True)[vertex]
# 0D algorithm
if self.geom is None:
self.geom = store_geom
- raise RuntimeError, "Attempt to create SegmentAroundVertex_0D algorithm on None shape"
+ raise RuntimeError("Attempt to create SegmentAroundVertex_0D algorithm on None shape")
from salome.smesh.smeshBuilder import AssureGeomPublished, GetName, TreatHypoStatus
AssureGeomPublished( self.mesh, self.geom )
name = GetName(self.geom)
## Return 3D hypothesis holding the 1D one
def Get3DHypothesis(self):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
return self.distribHyp
# hypothesis. Returns the created hypothesis
def OwnHypothesis(self, hypType, args=[], so="libStdMeshersEngine.so"):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
if not self.nbLayers is None:
self.mesh.GetMesh().RemoveHypothesis( self.geom, self.nbLayers )
self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
- study = self.mesh.smeshpyD.GetCurrentStudy() # prevents publishing own 1D hypothesis
- self.mesh.smeshpyD.SetCurrentStudy( None )
+ self.mesh.smeshpyD.SetEnablePublish( False ) # prevents publishing own 1D hypothesis
hyp = self.mesh.smeshpyD.CreateHypothesis(hypType, so)
- self.mesh.smeshpyD.SetCurrentStudy( study ) # enables publishing
+ self.mesh.smeshpyD.SetEnablePublish( True ) # enables publishing
if not self.distribHyp:
self.distribHyp = self.Hypothesis("LayerDistribution", UseExisting=0)
self.distribHyp.SetLayerDistribution( hyp )
# the same parameters, else (default) - creates a new one
def NumberOfLayers(self, n, UseExisting=0):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
self.mesh.RemoveHypothesis( self.distribHyp, self.geom )
from salome.smesh.smeshBuilder import IsEqual
# @param p the precision of rounding
def LocalLength(self, l, p=1e-07):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
hyp = self.OwnHypothesis("LocalLength", [l,p])
hyp.SetLength(l)
# @param s the scale factor (optional)
def NumberOfSegments(self, n, s=[]):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
if not s:
hyp = self.OwnHypothesis("NumberOfSegments", [n])
# @param end the length of the last segment
def Arithmetic1D(self, start, end ):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
hyp = self.OwnHypothesis("Arithmetic1D", [start, end])
hyp.SetLength(start, 1)
# @param ratio the common ratio of the geometric progression
def GeometricProgression(self, start, ratio ):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
hyp = self.OwnHypothesis("GeometricProgression", [start, ratio])
hyp.SetStartLength( start )
# @param end for the length of the last segment
def StartEndLength(self, start, end):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
hyp = self.OwnHypothesis("StartEndLength", [start, end])
hyp.SetLength(start, 1)
# @param fineness defines the quality of the mesh within the range [0-1]
def AutomaticLength(self, fineness=0):
if self.algoType != "RadialPrism_3D":
- print "Prism_3D algorith doesn't support any hyposesis"
+ print("Prism_3D algorith doesn't support any hyposesis")
return None
hyp = self.OwnHypothesis("AutomaticLength")
hyp.SetFineness( fineness )
self.distribHyp = self.Hypothesis("LayerDistribution2D", UseExisting=0)
else:
self.mesh.GetMesh().AddHypothesis( self.geom, self.distribHyp )
- study = self.mesh.smeshpyD.GetCurrentStudy() # prevents publishing own 1D hypothesis
- self.mesh.smeshpyD.SetCurrentStudy( None )
+ self.mesh.smeshpyD.SetEnablePublish( False )
hyp = self.mesh.smeshpyD.CreateHypothesis(hypType, so)
- self.mesh.smeshpyD.SetCurrentStudy( study ) # enables publishing
+ self.mesh.smeshpyD.SetEnablePublish( True )
self.distribHyp.SetLayerDistribution( hyp )
return hyp
self.mesh.AddHypothesis( self.hyp, self.geom )
for axis, gridDef in enumerate( [xGridDef, yGridDef, zGridDef] ):
- if not gridDef: raise ValueError, "Empty grid definition"
+ if not gridDef: raise ValueError("Empty grid definition")
if isinstance( gridDef, str ):
self.hyp.SetGridSpacing( [gridDef], [], axis )
elif isinstance( gridDef[0], str ):
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import os
# Values
# ------
- print "Output directory:", tmpDir
+tmpDir = os.getenv('SALOME_TMP_DIR', '/tmp')
++print("Output directory:", tmpDir)
+
# Path for ".med" files
-path = "/tmp/ex29_%s_" % os.getenv('USER','unknown')
+path = os.path.join( tmpDir, "ex29_%s_" % os.getenv('USER','unknown'))
# Name of the shape and the mesh
name = "Carre"
SplitTrianglesIn4(MyMesh)
NbCells2 = NbCells1*4
- print("Mesh with "+str(NbCells2)+" cells computed.")
+ print(("Mesh with "+str(NbCells2)+" cells computed."))
MyMesh.ExportMED(path+str(NbCells2)+"_triangles.med", 0)
SplitTrianglesIn4(MyMesh)
NbCells3 = NbCells2*4
- print("Mesh with "+str(NbCells3)+" cells computed.")
+ print(("Mesh with "+str(NbCells3)+" cells computed."))
MyMesh.ExportMED(path+str(NbCells3)+"_triangles.med",0)
SplitTrianglesIn4(MyMesh)
NbCells4 = NbCells3*4
- print("Mesh with "+str(NbCells4)+" cells computed.")
+ print(("Mesh with "+str(NbCells4)+" cells computed."))
MyMesh.ExportMED(path+str(NbCells4)+"_triangles.med", 0)
# Update the object browser
# -------------------------
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# Parameters
# ----------
# Define a mesh on a geometry
# ---------------------------
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
m = smesh.Mesh(cylinder)
algo3d.SetNbPart(4)
algo3d.SetBackground(False)
algo3d.SetKeepFiles(False)
- algo3d.SetToMeshHoles(True)
# Launch meshers
# --------------
# ----------
if os.access(results+".xml", os.F_OK):
- print "Ok: tepal"
+ print("Ok: tepal")
else:
- print "KO: tepal"
+ print("KO: tepal")
# Update object browser
# ---------------------
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import math
global Box_1
Box_1 = geompy.MakeBoxDXDYDZ(200, 200, 200)
geompy.addToStudy( Box_1, "Box_1" )
-smesh.SetCurrentStudy(salome.myStudy)
+smesh.UpdateStudy()
from salome.StdMeshers import StdMeshersBuilder
Mesh_1 = smesh.Mesh(Box_1)
Regular_1D = Mesh_1.Segment()
### CreateDimGroup()
- aListOf3d_1=range(721,821)
+ aListOf3d_1=list(range(721,821))
aGrp3D_1=Mesh_1.GetMesh().CreateGroup( SMESH.VOLUME, "Src 3D 1" )
aGrp3D_1.Add( aListOf3d_1 )
- aListOf3d_2=range(821, 921)
+ aListOf3d_2=list(range(821, 921))
aGrp3D_2=Mesh_1.GetMesh().CreateGroup( SMESH.VOLUME, "Src 3D 2" )
aGrp3D_2.Add( aListOf3d_2 )
aGrp0D = Mesh_1.CreateDimGroup( [aGrp3D_1, aGrp3D_2], SMESH.NODE, "Nodes" )
-salome.sg.updateObjBrowser(True)
+salome.sg.updateObjBrowser()
\brief Module smesh
"""
+ import inspect
import salome
from salome import *
try:
# get instance of class smeshBuilder
engineSmesh = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
- smesh = smeshBuilder.New(salome.myStudy, engineSmesh)
+ smesh = smeshBuilder.New(True,engineSmesh)
except:
- print "exception in smesh.py: instance creation failed"
+ print("exception in smesh.py: instance creation failed")
smesh = None
pass
# load plugins and add dynamically generated methods to Mesh class,
- # the same for for global variables declared by plug-ins
+ # the same for global variables declared by plug-ins
from salome.smesh.smeshBuilder import *
from salome.smesh.smeshBuilder import Mesh, algoCreator
for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
pluginBuilderName = pluginName + "Builder"
try:
exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
- except Exception, e:
+ except Exception as e:
from salome_utils import verbose
- if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
+ if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
continue
exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
plugin = eval( pluginBuilderName )
for k in dir( plugin ):
if k[0] == '_': continue
algo = getattr( plugin, k )
- if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
+ if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
if not hasattr( Mesh, algo.meshMethod ):
setattr( Mesh, algo.meshMethod, algoCreator() )
pass
# export the methods of smeshBuilder
if smesh:
for k in dir( smesh ):
- if k[0] == '_': continue
- globals()[k] = getattr( smesh, k )
+ if k[0] == '_': continue
+ globals()[k] = getattr( smesh, k )
del k
pass
- print """
+ print("""
===============================================================================
WARNING:
Usage of smesh.py is deprecated in SALOME V7.2!
TODO:
The following changes in your scripts are required to avoid this message:
- replace
+ replace
-------
import smesh, SMESH
-smesh.SetCurrentStudy(theStudy)
with
----
import SMESH
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
you also need to modify some lines where smeshBuilder is used instead of smesh
- algo=smesh.xxxx ==> algo=smeshBuilder.xxxx
+ algo=smesh.xxxx ==> algo=smeshBuilder.xxxx
See also SMESH User's Guide for more details
It does not work in the second, third, etc studies!
===============================================================================
- """
+ """)
import SALOME
import SALOMEDS
import os
+ import inspect
+
+ # In case the omniORBpy EnumItem class does not fully support Python 3
+ # (for instance in version 4.2.1-2), the comparison ordering methods must be
+ # defined
+ #
+ try:
+ SMESH.Entity_Triangle < SMESH.Entity_Quadrangle
+ except TypeError:
+ def enumitem_eq(self, other):
+ try:
+ if isinstance(other, omniORB.EnumItem):
+ if other._parent_id == self._parent_id:
+ return self._v == other._v
+ else:
+ return self._parent_id == other._parent_id
+ else:
+ return id(self) == id(other)
+ except:
+ return id(self) == id(other)
+
+ def enumitem_lt(self, other):
+ try:
+ if isinstance(other, omniORB.EnumItem):
+ if other._parent_id == self._parent_id:
+ return self._v < other._v
+ else:
+ return self._parent_id < other._parent_id
+ else:
+ return id(self) < id(other)
+ except:
+ return id(self) < id(other)
+
+ def enumitem_le(self, other):
+ try:
+ if isinstance(other, omniORB.EnumItem):
+ if other._parent_id == self._parent_id:
+ return self._v <= other._v
+ else:
+ return self._parent_id <= other._parent_id
+ else:
+ return id(self) <= id(other)
+ except:
+ return id(self) <= id(other)
+
+ def enumitem_gt(self, other):
+ try:
+ if isinstance(other, omniORB.EnumItem):
+ if other._parent_id == self._parent_id:
+ return self._v > other._v
+ else:
+ return self._parent_id > other._parent_id
+ else:
+ return id(self) > id(other)
+ except:
+ return id(self) > id(other)
+
+ def enumitem_ge(self, other):
+ try:
+ if isinstance(other, omniORB.EnumItem):
+ if other._parent_id == self._parent_id:
+ return self._v >= other._v
+ else:
+ return self._parent_id >= other._parent_id
+ else:
+ return id(self) >= id(other)
+ except:
+ return id(self) >= id(other)
+
+ omniORB.EnumItem.__eq__ = enumitem_eq
+ omniORB.EnumItem.__lt__ = enumitem_lt
+ omniORB.EnumItem.__le__ = enumitem_le
+ omniORB.EnumItem.__gt__ = enumitem_gt
+ omniORB.EnumItem.__ge__ = enumitem_ge
+
## Private class used to workaround a problem that sometimes isinstance(m, Mesh) returns False
#
Parameters = ""
hasVariables = False
varModifFun=None
- if args and callable( args[-1] ):
+ if args and callable(args[-1]):
args, varModifFun = args[:-1], args[-1]
for parameter in args:
if isinstance(parameter,str):
# check if there is an inexistent variable name
if not notebook.isVariable(parameter):
- raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
+ raise ValueError("Variable with name '" + parameter + "' doesn't exist!!!")
parameter = notebook.get(parameter)
hasVariables = True
if varModifFun:
# Parameters are stored in AxisStruct.parameters attribute
def __initAxisStruct(ax,*args):
if len( args ) != 6:
- raise RuntimeError,\
- "Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args ))
+ raise RuntimeError("Bad nb args (%s) passed in SMESH.AxisStruct(x,y,z,dx,dy,dz)"%(len( args )))
ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
pass
SMESH.AxisStruct.__init__ = __initAxisStruct
except:
ior = None
if ior:
- # CORBA object
- studies = salome.myStudyManager.GetOpenStudies()
- for sname in studies:
- s = salome.myStudyManager.GetStudyByName(sname)
- if not s: continue
- sobj = s.FindObjectIOR(ior)
- if not sobj: continue
+ sobj = salome.myStudy.FindObjectIOR(ior)
+ if sobj:
return sobj.GetName()
if hasattr(obj, "GetName"):
# unknown CORBA object, having GetName() method
# unknown non-CORBA object, having GetName() method
return obj.GetName()
pass
- raise RuntimeError, "Null or invalid object"
+ raise RuntimeError("Null or invalid object")
## Print error message if a hypothesis was not assigned.
def TreatHypoStatus(status, hypName, geomName, isAlgo, mesh):
pass
reason = ""
if hasattr( status, "__getitem__" ):
- status,reason = status[0],status[1]
- if status == HYP_UNKNOWN_FATAL :
+ status, reason = status[0], status[1]
+ if status == HYP_UNKNOWN_FATAL:
reason = "for unknown reason"
- elif status == HYP_INCOMPATIBLE :
+ elif status == HYP_INCOMPATIBLE:
reason = "this hypothesis mismatches the algorithm"
- elif status == HYP_NOTCONFORM :
+ elif status == HYP_NOTCONFORM:
reason = "a non-conform mesh would be built"
- elif status == HYP_ALREADY_EXIST :
+ elif status == HYP_ALREADY_EXIST:
if isAlgo: return # it does not influence anything
reason = hypType + " of the same dimension is already assigned to this shape"
- elif status == HYP_BAD_DIM :
+ elif status == HYP_BAD_DIM:
reason = hypType + " mismatches the shape"
- elif status == HYP_CONCURENT :
+ elif status == HYP_CONCURENT:
reason = "there are concurrent hypotheses on sub-shapes"
- elif status == HYP_BAD_SUBSHAPE :
+ elif status == HYP_BAD_SUBSHAPE:
reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
elif status == HYP_BAD_GEOMETRY:
reason = "the algorithm is not applicable to this geometry"
if meshName and meshName != NO_NAME:
where = '"%s" shape in "%s" mesh ' % ( geomName, meshName )
if status < HYP_UNKNOWN_FATAL and where:
- print '"%s" was assigned to %s but %s' %( hypName, where, reason )
+ print('"%s" was assigned to %s but %s' %( hypName, where, reason ))
elif where:
- print '"%s" was not assigned to %s : %s' %( hypName, where, reason )
+ print('"%s" was not assigned to %s : %s' %( hypName, where, reason ))
else:
- print '"%s" was not assigned : %s' %( hypName, reason )
+ print('"%s" was not assigned : %s' %( hypName, reason ))
pass
## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
def AssureGeomPublished(mesh, geom, name=''):
if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
return
- if not geom.GetStudyEntry() and \
- mesh.smeshpyD.GetCurrentStudy():
- ## set the study
- studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
- if studyID != mesh.geompyD.myStudyId:
- mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
+ if not geom.GetStudyEntry():
## get a name
if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
# for all groups SubShapeName() return "Compound_-1"
def FirstVertexOnCurve(mesh, edge):
vv = mesh.geompyD.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
if not vv:
- raise TypeError, "Given object has no vertices"
+ raise TypeError("Given object has no vertices")
if len( vv ) == 1: return vv[0]
v0 = mesh.geompyD.MakeVertexOnCurve(edge,0.)
xyz = mesh.geompyD.PointCoordinates( v0 ) # coords of the first vertex
else:
return vv[1]
+ ## Return a long value from enumeration
+ def EnumToLong(theItem):
+ return theItem._v
+
# end of l1_auxiliary
## @}
## This class allows to create, load or manipulate meshes.
# It has a set of methods to create, load or copy meshes, to combine several meshes, etc.
# It also has methods to get infos and measure meshes.
- class smeshBuilder(object, SMESH._objref_SMESH_Gen):
+ class smeshBuilder(SMESH._objref_SMESH_Gen):
# MirrorType enumeration
POINT = SMESH_MeshEditor.POINT
PrecisionConfusion = smeshPrecisionConfusion
# TopAbs_State enumeration
- [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
+ [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = list(range(4))
# Methods of splitting a hexahedron into tetrahedra
Hex_5Tet, Hex_6Tet, Hex_24Tet, Hex_2Prisms, Hex_4Prisms = 1, 2, 3, 1, 2
- def __new__(cls):
+ def __new__(cls, *args):
global engine
global smeshInst
global doLcc
#print "====2 ", smeshInst
return smeshInst
- def __init__(self):
+ def __init__(self, *args):
global created
#print "--------------- smeshbuilder __init__ ---", created
if not created:
- created = True
- SMESH._objref_SMESH_Gen.__init__(self)
+ created = True
+ SMESH._objref_SMESH_Gen.__init__(self, *args)
## Dump component to the Python script
# This method overrides IDL function to allow default values for the parameters.
# @ingroup l1_auxiliary
- def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
- return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
+ def DumpPython(self, theIsPublished=True, theIsMultiFile=True):
+ return SMESH._objref_SMESH_Gen.DumpPython(self, theIsPublished, theIsMultiFile)
## Set mode of DumpPython(), \a historical or \a snapshot.
# In the \a historical mode, the Python Dump script includes all commands
else: val = "false"
SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
- ## Set the current study and Geometry component
+ ## Set Geometry component
# @ingroup l1_auxiliary
- def init_smesh(self,theStudy,geompyD = None):
+ def init_smesh(self,isPublished = True,geompyD = None):
#print "init_smesh"
- self.SetCurrentStudy(theStudy,geompyD)
- if theStudy:
+ self.UpdateStudy(geompyD)
+ if isPublished:
global notebook
- notebook.myStudy = theStudy
+ notebook.myStudy = salome.myStudy
## Create a mesh. This can be either an empty mesh, possibly having an underlying geometry,
# or a mesh wrapping a CORBA mesh given as a parameter.
obj,name = name,obj
return Mesh(self,self.geompyD,obj,name)
- ## Return a long value from enumeration
- # @ingroup l1_auxiliary
- def EnumToLong(self,theItem):
- return theItem._v
-
## Return a string representation of the color.
# To be used with filters.
# @param c color value (SALOMEDS.Color)
elif isinstance(c, str):
val = c
else:
- raise ValueError, "Color value should be of string or SALOMEDS.Color type"
+ raise ValueError("Color value should be of string or SALOMEDS.Color type")
return val
## Get PointStruct from vertex
def GetDirStruct(self,theVector):
vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
if(len(vertices) != 2):
- print "Error: vector object is incorrect."
+ print("Error: vector object is incorrect.")
return None
p1 = self.geompyD.PointCoordinates(vertices[0])
p2 = self.geompyD.PointCoordinates(vertices[1])
# @ingroup l1_auxiliary
def IsEmbeddedMode(self):
return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
-
- ## Set the current study. Calling SetCurrentStudy( None ) allows to
- # switch OFF automatic pubilishing in the Study of mesh objects.
+
+ ## Update the current study. Calling UpdateStudy() allows to
+ # update meshes at switching GEOM->SMESH
# @ingroup l1_auxiliary
- def SetCurrentStudy( self, theStudy, geompyD = None ):
+ def UpdateStudy( self, geompyD = None ):
+ #self.UpdateStudy()
if not geompyD:
from salome.geom import geomBuilder
geompyD = geomBuilder.geom
pass
self.geompyD=geompyD
self.SetGeomEngine(geompyD)
- SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
- global notebook
- if theStudy:
- notebook = salome_notebook.NoteBook( theStudy )
- else:
- notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
- if theStudy:
- sb = theStudy.NewBuilder()
- sc = theStudy.FindComponent("SMESH")
- if sc: sb.LoadWith(sc, self)
- pass
+ SMESH._objref_SMESH_Gen.UpdateStudy(self)
+ sb = salome.myStudy.NewBuilder()
+ sc = salome.myStudy.FindComponent("SMESH")
+ if sc: sb.LoadWith(sc, self)
pass
-
- ## Get the current study
+
+ ## Sets enable publishing in the study. Calling SetEnablePublish( false ) allows to
+ # switch OFF publishing in the Study of mesh objects.
# @ingroup l1_auxiliary
- def GetCurrentStudy(self):
- return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
+ def SetEnablePublish( self, theIsEnablePublish ):
+ #self.SetEnablePublish(theIsEnablePublish)
+ SMESH._objref_SMESH_Gen.SetEnablePublish(self,theIsEnablePublish)
+ global notebook
+ notebook = salome_notebook.NoteBook( theIsEnablePublish )
## Create a Mesh object importing data from the given UNV file
# @return an instance of Mesh class
aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
theFileName,
True)
- if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
+ if error.comment: print("*** CreateMeshesFromGMF() errors:\n", error.comment)
return Mesh(self, self.geompyD, aSmeshMesh), error
## Concatenate the given meshes into one mesh. All groups of input meshes will be
def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
- ## Create a pattern mapper.
+ ## Create a pattern mapper.
# @return an instance of SMESH_Pattern
#
# <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
# @return SMESH.Filter.Criterion
# @ingroup l1_controls
def GetEmptyCriterion(self):
- Type = self.EnumToLong(FT_Undefined)
- Compare = self.EnumToLong(FT_Undefined)
+ Type = EnumToLong(FT_Undefined)
+ Compare = EnumToLong(FT_Undefined)
Threshold = 0
ThresholdStr = ""
ThresholdID = ""
- UnaryOp = self.EnumToLong(FT_Undefined)
- BinaryOp = self.EnumToLong(FT_Undefined)
+ UnaryOp = EnumToLong(FT_Undefined)
+ BinaryOp = EnumToLong(FT_Undefined)
Tolerance = 1e-07
TypeOfElement = ALL
Precision = -1 ##@1e-07
BinaryOp=FT_Undefined,
Tolerance=1e-07):
if not CritType in SMESH.FunctorType._items:
- raise TypeError, "CritType should be of SMESH.FunctorType"
+ raise TypeError("CritType should be of SMESH.FunctorType")
aCriterion = self.GetEmptyCriterion()
aCriterion.TypeOfElement = elementType
- aCriterion.Type = self.EnumToLong(CritType)
+ aCriterion.Type = EnumToLong(CritType)
aCriterion.Tolerance = Tolerance
aThreshold = Threshold
if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
- aCriterion.Compare = self.EnumToLong(Compare)
+ aCriterion.Compare = EnumToLong(Compare)
elif Compare == "=" or Compare == "==":
- aCriterion.Compare = self.EnumToLong(FT_EqualTo)
+ aCriterion.Compare = EnumToLong(FT_EqualTo)
elif Compare == "<":
- aCriterion.Compare = self.EnumToLong(FT_LessThan)
+ aCriterion.Compare = EnumToLong(FT_LessThan)
elif Compare == ">":
- aCriterion.Compare = self.EnumToLong(FT_MoreThan)
+ aCriterion.Compare = EnumToLong(FT_MoreThan)
elif Compare != FT_Undefined:
- aCriterion.Compare = self.EnumToLong(FT_EqualTo)
+ aCriterion.Compare = EnumToLong(FT_EqualTo)
aThreshold = Compare
if CritType in [FT_BelongToGeom, FT_BelongToPlane, FT_BelongToGenSurface,
elif isinstance( aThreshold, str ):
aCriterion.ThresholdStr = aThreshold
else:
- raise TypeError, "The Threshold should be a shape."
+ raise TypeError("The Threshold should be a shape.")
if isinstance(UnaryOp,float):
aCriterion.Tolerance = UnaryOp
UnaryOp = FT_Undefined
# Check that Threshold is a group
if isinstance(aThreshold, SMESH._objref_SMESH_GroupBase):
if aThreshold.GetType() != elementType:
- raise ValueError, "Group type mismatches Element type"
+ raise ValueError("Group type mismatches Element type")
aCriterion.ThresholdStr = aThreshold.GetName()
aCriterion.ThresholdID = salome.orb.object_to_string( aThreshold )
- study = self.GetCurrentStudy()
+ study = salome.myStudy
if study:
so = study.FindObjectIOR( aCriterion.ThresholdID )
if so:
if entry:
aCriterion.ThresholdID = entry
else:
- raise TypeError, "The Threshold should be a Mesh Group"
+ raise TypeError("The Threshold should be a Mesh Group")
elif CritType == FT_RangeOfIds:
# Check that Threshold is string
if isinstance(aThreshold, str):
aCriterion.ThresholdStr = aThreshold
else:
- raise TypeError, "The Threshold should be a string."
+ raise TypeError("The Threshold should be a string.")
elif CritType == FT_CoplanarFaces:
# Check the Threshold
if isinstance(aThreshold, int):
elif isinstance(aThreshold, str):
ID = int(aThreshold)
if ID < 1:
- raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
+ raise ValueError("Invalid ID of mesh face: '%s'"%aThreshold)
aCriterion.ThresholdID = aThreshold
else:
- raise TypeError,\
- "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
+ raise TypeError("The Threshold should be an ID of mesh face and not '%s'"%aThreshold)
elif CritType == FT_ConnectedElements:
# Check the Threshold
if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object): # shape
aCriterion.Threshold = aThreshold
elif isinstance(aThreshold, list): # 3 point coordinates
if len( aThreshold ) < 3:
- raise ValueError, "too few point coordinates, must be 3"
+ raise ValueError("too few point coordinates, must be 3")
aCriterion.ThresholdStr = " ".join( [str(c) for c in aThreshold[:3]] )
elif isinstance(aThreshold, str):
if aThreshold.isdigit():
else:
aCriterion.ThresholdStr = aThreshold # hope that it's point coordinates
else:
- raise TypeError,\
- "The Threshold should either a VERTEX, or a node ID, "\
- "or a list of point coordinates and not '%s'"%aThreshold
+ raise TypeError("The Threshold should either a VERTEX, or a node ID, "\
+ "or a list of point coordinates and not '%s'"%aThreshold)
elif CritType == FT_ElemGeomType:
# Check the Threshold
try:
- aCriterion.Threshold = self.EnumToLong(aThreshold)
+ aCriterion.Threshold = EnumToLong(aThreshold)
assert( aThreshold in SMESH.GeometryType._items )
except:
if isinstance(aThreshold, int):
aCriterion.Threshold = aThreshold
else:
- raise TypeError, "The Threshold should be an integer or SMESH.GeometryType."
+ raise TypeError("The Threshold should be an integer or SMESH.GeometryType.")
pass
pass
elif CritType == FT_EntityType:
# Check the Threshold
try:
- aCriterion.Threshold = self.EnumToLong(aThreshold)
+ aCriterion.Threshold = EnumToLong(aThreshold)
assert( aThreshold in SMESH.EntityType._items )
except:
if isinstance(aThreshold, int):
aCriterion.Threshold = aThreshold
else:
- raise TypeError, "The Threshold should be an integer or SMESH.EntityType."
+ raise TypeError("The Threshold should be an integer or SMESH.EntityType.")
pass
pass
-
+
elif CritType == FT_GroupColor:
# Check the Threshold
try:
aCriterion.ThresholdStr = self.ColorToString(aThreshold)
except:
- raise TypeError, "The threshold value should be of SALOMEDS.Color type"
+ raise TypeError("The threshold value should be of SALOMEDS.Color type")
pass
elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
FT_LinearOrQuadratic, FT_BadOrientedVolume,
FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
# At this point the Threshold is unnecessary
if aThreshold == FT_LogicalNOT:
- aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
+ aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
aCriterion.BinaryOp = aThreshold
else:
aThreshold = float(aThreshold)
aCriterion.Threshold = aThreshold
except:
- raise TypeError, "The Threshold should be a number."
+ raise TypeError("The Threshold should be a number.")
return None
if Threshold == FT_LogicalNOT or UnaryOp == FT_LogicalNOT:
- aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
+ aCriterion.UnaryOp = EnumToLong(FT_LogicalNOT)
if Threshold in [FT_LogicalAND, FT_LogicalOR]:
- aCriterion.BinaryOp = self.EnumToLong(Threshold)
+ aCriterion.BinaryOp = EnumToLong(Threshold)
if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
- aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
+ aCriterion.BinaryOp = EnumToLong(UnaryOp)
if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
- aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
+ aCriterion.BinaryOp = EnumToLong(BinaryOp)
return aCriterion
# @ingroup l1_controls
def GetFilterFromCriteria(self,criteria, binOp=SMESH.FT_LogicalAND):
for i in range( len( criteria ) - 1 ):
- if criteria[i].BinaryOp == self.EnumToLong( SMESH.FT_Undefined ):
- criteria[i].BinaryOp = self.EnumToLong( binOp )
+ if criteria[i].BinaryOp == EnumToLong( SMESH.FT_Undefined ):
+ criteria[i].BinaryOp = EnumToLong( binOp )
aFilterMgr = self.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aFilter.SetCriteria(criteria)
elif theCriterion == FT_BallDiameter:
functor = aFilterMgr.CreateBallDiameter()
else:
- print "Error: given parameter is not numerical functor type."
+ print("Error: given parameter is not numerical functor type.")
aFilterMgr.UnRegister()
return functor
d = {}
if hasattr(obj, "GetMeshInfo"):
values = obj.GetMeshInfo()
- for i in range(SMESH.Entity_Last._v):
+ for i in range(EnumToLong(SMESH.Entity_Last)):
if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
pass
return d
# import salome
# salome.salome_init()
# from salome.smesh import smeshBuilder
-# smesh = smeshBuilder.New(salome.myStudy)
+# smesh = smeshBuilder.New()
# \endcode
-# @param study SALOME study, generally obtained by salome.myStudy.
+# @param isPublished If False, the notebool will not be used.
# @param instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
# @return smeshBuilder instance
-def New( study, instance=None):
+def New( isPublished = True, instance=None):
"""
Create a new smeshBuilder instance.The smeshBuilder class provides the Python
interface to create or load meshes.
import salome
salome.salome_init()
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
Parameters:
- study SALOME study, generally obtained by salome.myStudy.
+ isPublished If False, the notebool will not be used.
instance CORBA proxy of SMESH Engine. If None, the default Engine is used.
Returns:
smeshBuilder instance
global doLcc
engine = instance
if engine is None:
- doLcc = True
+ doLcc = True
smeshInst = smeshBuilder()
assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
- smeshInst.init_smesh(study)
+ smeshInst.init_smesh(isPublished)
return smeshInst
# It also has methods to define groups of mesh elements, to modify a mesh (by addition of
# new nodes and elements and by changing the existing entities), to get information
# about a mesh and to export a mesh in different formats.
- class Mesh:
- __metaclass__ = MeshMeta
-
+ class Mesh(metaclass=MeshMeta):
geom = 0
mesh = 0
editor = 0
# @param name Study name of the mesh
# @ingroup l2_construct
def __init__(self, smeshpyD, geompyD, obj=0, name=0):
- self.smeshpyD=smeshpyD
- self.geompyD=geompyD
+ self.smeshpyD = smeshpyD
+ self.geompyD = geompyD
if obj is None:
obj = 0
objHasName = False
self.geom = obj
objHasName = True
# publish geom of mesh (issue 0021122)
- if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
+ if not self.geom.GetStudyEntry():
objHasName = False
- studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
- if studyID != geompyD.myStudyId:
- geompyD.init_geom( smeshpyD.GetCurrentStudy())
- pass
+ geompyD.init_geom()
if name:
geo_name = name + " shape"
else:
self.geom = self.mesh.GetShapeToMesh()
self.editor = self.mesh.GetMeshEditor()
- self.functors = [None] * SMESH.FT_Undefined._v
+ self.functors = [None] * EnumToLong(SMESH.FT_Undefined)
# set self to algoCreator's
for attrName in dir(self):
#self.mesh.UnRegister()
pass
pass
-
+
## Initialize the Mesh object from an instance of SMESH_Mesh interface
# @param theMesh a SMESH_Mesh object
# @ingroup l2_construct
if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
self.mesh.Clear()
ok = self.smeshpyD.Compute(self.mesh, geom)
- except SALOME.SALOME_Exception, ex:
- print "Mesh computation failed, exception caught:"
- print " ", ex.details.text
+ except SALOME.SALOME_Exception as ex:
+ print("Mesh computation failed, exception caught:")
+ print(" ", ex.details.text)
except:
import traceback
- print "Mesh computation failed, exception caught:"
+ print("Mesh computation failed, exception caught:")
traceback.print_exc()
if True:#not ok:
allReasons = ""
else: msg += " has not been computed"
if allReasons != "": msg += ":"
else: msg += "."
- print msg
- print allReasons
+ print(msg)
+ print(allReasons)
pass
- if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
+ if salome.sg.hasDesktop():
if not isinstance( refresh, list): # not a call from subMesh.Compute()
smeshgui = salome.ImportComponentGUI("SMESH")
- smeshgui.Init(self.mesh.GetStudyId())
+ smeshgui.Init()
smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
- if refresh: salome.sg.updateObjBrowser(True)
+ if refresh: salome.sg.updateObjBrowser()
return ok
try:
shapeText = ""
mainIOR = salome.orb.object_to_string( self.GetShape() )
- for sname in salome.myStudyManager.GetOpenStudies():
- s = salome.myStudyManager.GetStudyByName(sname)
- if not s: continue
- mainSO = s.FindObjectIOR(mainIOR)
- if not mainSO: continue
+ s = salome.myStudy
+ mainSO = s.FindObjectIOR(mainIOR)
+ if mainSO:
if subShapeID == 1:
shapeText = '"%s"' % mainSO.GetName()
subIt = s.NewChildIterator(mainSO)
continue
if ids == subShapeID:
shapeText = '"%s"' % subSO.GetName()
- break
if not shapeText:
shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
if shape:
pass
groups = []
- for algoName, shapes in algo2shapes.items():
+ for algoName, shapes in list(algo2shapes.items()):
while shapes:
- groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
+ groupType = EnumToLong( shapes[0].GetShapeType() )
otherTypeShapes = []
sameTypeShapes = []
group = self.geompyD.CreateGroup( self.geom, groupType )
# @ingroup l2_construct
def Clear(self, refresh=False):
self.mesh.Clear()
- if ( salome.sg.hasDesktop() and
- salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
+ if ( salome.sg.hasDesktop() ):
smeshgui = salome.ImportComponentGUI("SMESH")
- smeshgui.Init(self.mesh.GetStudyId())
+ smeshgui.Init()
smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
- if refresh: salome.sg.updateObjBrowser(True)
+ if refresh: salome.sg.updateObjBrowser()
## Remove all nodes and elements of indicated shape
# @param refresh if @c True, Object browser is automatically updated (when running in GUI)
self.mesh.ClearSubMesh(geomId)
if salome.sg.hasDesktop():
smeshgui = salome.ImportComponentGUI("SMESH")
- smeshgui.Init(self.mesh.GetStudyId())
+ smeshgui.Init()
smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
- if refresh: salome.sg.updateObjBrowser(True)
+ if refresh: salome.sg.updateObjBrowser()
## Compute a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
# @param fineness [0.0,1.0] defines mesh fineness
AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
status = self.mesh.AddHypothesis(geom, hyp)
else:
- status = HYP_BAD_GEOMETRY,""
+ status = HYP_BAD_GEOMETRY, ""
hyp_name = GetName( hyp )
geom_name = ""
if geom:
return self.mesh.RemoveHypothesis( shape, hyp )
hypName = GetName( hyp )
geoName = GetName( shape )
- print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
+ print("WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName ))
return None
## Get the list of hypotheses added on a geometry
# - 3D in the rest cases.<br>
# If @a autoDimension is @c False, the space dimension is always 3.
# @param fields list of GEOM fields defined on the shape to mesh.
- # @param geomAssocFields each character of this string means a need to export a
+ # @param geomAssocFields each character of this string means a need to export a
# corresponding field; correspondence between fields and characters is following:
# - 'v' stands for "_vertices _" field;
# - 'e' stands for "_edges _" field;
# ----------------------
## Create an empty mesh group
- # @param elementType the type of elements in the group; either of
+ # @param elementType the type of elements in the group; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
# @param name the name of the mesh group
# @return SMESH_Group
# the name is the same as the geometrical group name
# @param grp a geometrical group, a vertex, an edge, a face or a solid
# @param name the name of the mesh group
- # @param typ the type of elements in the group; either of
+ # @param typ the type of elements in the group; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
# automatically detected by the type of the geometry
# @return SMESH_GroupOnGeom
elif tgeo == "COMPOUND":
sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
if not sub:
- raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
+ raise ValueError("_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape))
return self._groupTypeFromShape( sub[0] )
else:
- raise ValueError, \
- "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
+ raise ValueError("_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape))
return typ
## Create a mesh group with given \a name based on the \a filter which
## is a special type of group dynamically updating it's contents during
## mesh modification
- # @param typ the type of elements in the group; either of
+ # @param typ the type of elements in the group; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
# @param name the name of the mesh group
# @param filter the filter defining group contents
## Create a mesh group by the given ids of elements
# @param groupName the name of the mesh group
- # @param elementType the type of elements in the group; either of
+ # @param elementType the type of elements in the group; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
# @param elemIDs either the list of ids, group, sub-mesh, or filter
# @return SMESH_Group
## Get the list of groups existing in the mesh in the order
# of creation (starting from the oldest one)
- # @param elemType type of elements the groups contain; either of
+ # @param elemType type of elements the groups contain; either of
# (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
# by default groups of elements of all types are returned
# @return a sequence of SMESH_GroupBase
## Find groups by name and type
# @param name name of the group of interest
- # @param elemType type of elements the groups contain; either of
+ # @param elemType type of elements the groups contain; either of
# (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
# by default one group of any type of elements is returned
# if elemType == SMESH.ALL then all groups of any type are returned
if group.GetName() == name:
if elemType is None:
return [group]
- if ( elemType == SMESH.ALL or
+ if ( elemType == SMESH.ALL or
group.GetType() == elemType ):
groups.append( group )
return groups
# @return an instance of SMESH_Group
# @ingroup l2_grps_operon
def UnionListOfGroups(self, groups, name):
- return self.mesh.UnionListOfGroups(groups, name)
+ return self.mesh.UnionListOfGroups(groups, name)
## Prodice an intersection of two groups.
# A new group is created. All mesh elements that are common
# @return an instance of SMESH_Group
# @ingroup l2_grps_operon
def IntersectListOfGroups(self, groups, name):
- return self.mesh.IntersectListOfGroups(groups, name)
+ return self.mesh.IntersectListOfGroups(groups, name)
## Produce a cut of two groups.
# A new group is created. All mesh elements that are present in
##
# Create a standalone group of entities basing on nodes of other groups.
# \param groups - list of reference groups, sub-meshes or filters, of any type.
- # \param elemType - a type of elements to include to the new group; either of
+ # \param elemType - a type of elements to include to the new group; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
# \param name - a name of the new group.
# \param nbCommonNodes - a criterion of inclusion of an element to the new group
def GetId(self):
return self.mesh.GetId()
- ## Get the study Id
- # @return integer value, which is the study Id of the mesh
- # @ingroup l1_auxiliary
- def GetStudyId(self):
- return self.mesh.GetStudyId()
-
## Check the group names for duplications.
# Consider the maximum group name length stored in MED file.
# @return True or False
## Return an element based on all given nodes.
# @ingroup l1_meshinfo
- def FindElementByNodes(self,nodes):
+ def FindElementByNodes(self, nodes):
return self.mesh.FindElementByNodes(nodes)
+ ## Return elements including all given nodes.
+ # @ingroup l1_meshinfo
+ def GetElementsByNodes(self, nodes, elemType=SMESH.ALL):
+ return self.mesh.GetElementsByNodes( nodes, elemType )
+
## Return true if the given element is a polygon
# @ingroup l1_meshinfo
def IsPoly(self, id):
def Add0DElement( self, IDOfNode, DuplicateElements=True ):
return self.editor.Add0DElement( IDOfNode, DuplicateElements )
- ## Create 0D elements on all nodes of the given elements except those
+ ## Create 0D elements on all nodes of the given elements except those
# nodes on which a 0D element already exists.
# @param theObject an object on whose nodes 0D elements will be created.
# It can be mesh, sub-mesh, group, list of element IDs or a holder
# and/or found on nodes of \a theObject.
# @param DuplicateElements to add one more 0D element to a node or not
# @return an object (a new group or a temporary SMESH_IDSource) holding
- # IDs of new and/or found 0D elements. IDs of 0D elements
+ # IDs of new and/or found 0D elements. IDs of 0D elements
# can be retrieved from the returned object by calling GetIDs()
# @ingroup l2_modif_add
def Add0DElementsToAllNodes(self, theObject, theGroupName="", DuplicateElements=False):
VertexID = Vertex
try:
self.editor.SetNodeOnVertex(NodeID, VertexID)
- except SALOME.SALOME_Exception, inst:
- raise ValueError, inst.details.text
+ except SALOME.SALOME_Exception as inst:
+ raise ValueError(inst.details.text)
return True
EdgeID = Edge
try:
self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
- except SALOME.SALOME_Exception, inst:
- raise ValueError, inst.details.text
+ except SALOME.SALOME_Exception as inst:
+ raise ValueError(inst.details.text)
return True
## @brief Stores node position on a face
FaceID = Face
try:
self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
- except SALOME.SALOME_Exception, inst:
- raise ValueError, inst.details.text
+ except SALOME.SALOME_Exception as inst:
+ raise ValueError(inst.details.text)
return True
## @brief Binds a node to a solid
SolidID = Solid
try:
self.editor.SetNodeInVolume(NodeID, SolidID)
- except SALOME.SALOME_Exception, inst:
- raise ValueError, inst.details.text
+ except SALOME.SALOME_Exception as inst:
+ raise ValueError(inst.details.text)
return True
## @brief Bind an element to a shape
ShapeID = Shape
try:
self.editor.SetMeshElementOnShape(ElementID, ShapeID)
- except SALOME.SALOME_Exception, inst:
- raise ValueError, inst.details.text
+ except SALOME.SALOME_Exception as inst:
+ raise ValueError(inst.details.text)
return True
# @param x the X coordinate of a point
# @param y the Y coordinate of a point
# @param z the Z coordinate of a point
- # @param elementType type of elements to find; either of
+ # @param elementType type of elements to find; either of
# (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
# means elements of any type excluding nodes, discrete and 0D elements.
# @param meshPart a part of mesh (group, sub-mesh) to search within
pattern = self.smeshpyD.GetPattern()
isDone = pattern.LoadFromFile(pattern_tetra)
if not isDone:
- print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
+ print('Pattern.LoadFromFile :', pattern.GetErrorCode())
return isDone
pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
isDone = pattern.MakeMesh(self.mesh, False, False)
- if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
+ if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
# split quafrangle faces near triangular facets of volumes
self.SplitQuadsNearTriangularFacets()
pattern = self.smeshpyD.GetPattern()
isDone = pattern.LoadFromFile(pattern_prism)
if not isDone:
- print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
+ print('Pattern.LoadFromFile :', pattern.GetErrorCode())
return isDone
pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
isDone = pattern.MakeMesh(self.mesh, False, False)
- if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
+ if not isDone: print('Pattern.MakeMesh :', pattern.GetErrorCode())
# Split quafrangle faces near triangular facets of volumes
self.SplitQuadsNearTriangularFacets()
self.editor.ConvertToQuadratic(theForce3d)
error = self.editor.GetLastError()
if error and error.comment:
- print error.comment
+ print(error.comment)
return error
-
+
## Convert the mesh from quadratic to ordinary,
# deletes old quadratic elements, \n replacing
# them with ordinary mesh elements with the same id.
return mesh, group
##
- # @brief Create missing boundary elements around either the whole mesh or
+ # @brief Create missing boundary elements around either the whole mesh or
# groups of elements
# @param dimension - defines type of boundary elements to create, either of
# { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
# @param groupName - a name of group to store all boundary elements in,
# "" means not to create the group
- # @param meshName - a name of a new mesh, which is a copy of the initial
+ # @param meshName - a name of a new mesh, which is a copy of the initial
# mesh + created boundary elements; "" means not to create the new mesh
# @param toCopyAll - if true, the whole initial mesh will be copied into
# the new mesh else only boundary elements will be copied into the new mesh
if isinstance( basePoint, int):
xyz = self.GetNodeXYZ( basePoint )
if not xyz:
- raise RuntimeError, "Invalid node ID: %s" % basePoint
+ raise RuntimeError("Invalid node ID: %s" % basePoint)
basePoint = xyz
if isinstance( basePoint, geomBuilder.GEOM._objref_GEOM_Object ):
basePoint = self.geompyD.PointCoordinates( basePoint )
Elements = [ Elements.GetMesh() ]
if isinstance( Elements, list ):
if not Elements:
- raise RuntimeError, "Elements empty!"
+ raise RuntimeError("Elements empty!")
if isinstance( Elements[0], int ):
Elements = self.GetIDSource( Elements, SMESH.ALL )
unRegister.set( Elements )
if ( isinstance( thePoint, list )):
thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
if ( isinstance( theScaleFact, float )):
- theScaleFact = [theScaleFact]
+ theScaleFact = [theScaleFact]
if ( isinstance( theScaleFact, int )):
- theScaleFact = [ float(theScaleFact)]
+ theScaleFact = [ float(theScaleFact)]
self.mesh.SetParameters(thePoint.parameters)
if ( isinstance( thePoint, list )):
thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
if ( isinstance( theScaleFact, float )):
- theScaleFact = [theScaleFact]
+ theScaleFact = [theScaleFact]
if ( isinstance( theScaleFact, int )):
- theScaleFact = [ float(theScaleFact)]
+ theScaleFact = [ float(theScaleFact)]
self.mesh.SetParameters(thePoint.parameters)
mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
# @ingroup l2_modif_trsf
def FindCoincidentFreeBorders (self, tolerance=0.):
return self.editor.FindCoincidentFreeBorders( tolerance )
-
+
## Sew FreeBorder's of each group
# @param freeBorders either a SMESH.CoincidentFreeBorders structure or a list of lists
# where each enclosed list contains node IDs of a group of coincident free
coincidentGroups = []
for nodeList in freeBorders:
if not nodeList or len( nodeList ) % 3:
- raise ValueError, "Wrong number of nodes in this group: %s" % nodeList
+ raise ValueError("Wrong number of nodes in this group: %s" % nodeList)
group = []
while nodeList:
group.append ( SMESH.FreeBorderPart( len(borders), 0, 1, 2 ))
def ClearLastCreated(self):
self.editor.ClearLastCreated()
- ## Create duplicates of given elements, i.e. create new elements based on the
+ ## Create duplicates of given elements, i.e. create new elements based on the
# same nodes as the given ones.
# @param theElements - container of elements to duplicate. It can be a Mesh,
# sub-mesh, group, filter or a list of element IDs. If \a theElements is
# @param theGroupName - a name of group to contain the generated elements.
# If a group with such a name already exists, the new elements
# are added to the existng group, else a new group is created.
- # If \a theGroupName is empty, new elements are not added
+ # If \a theGroupName is empty, new elements are not added
# in any group.
# @return a group where the new elements are added. None if theGroupName == "".
# @ingroup l2_modif_duplicat
# @return TRUE if operation has been completed successfully, FALSE otherwise
# @ingroup l2_modif_duplicat
def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
- return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
+ return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
## Double nodes on some external faces and create flat elements.
# Flat elements are mainly used by some types of mechanic calculations.
- #
+ #
# Each group of the list must be constituted of faces.
# Triangles are transformed in prisms, and quadrangles in hexahedrons.
# @param theGroupsOfFaces - list of groups of faces
# @ingroup l2_modif_duplicat
def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
-
+
## identify all the elements around a geom shape, get the faces delimiting the hole
#
def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
def _getFunctor(self, funcType ):
- fn = self.functors[ funcType._v ]
+ fn = self.functors[ EnumToLong(funcType) ]
if not fn:
fn = self.smeshpyD.GetFunctor(funcType)
fn.SetMesh(self.mesh)
- self.functors[ funcType._v ] = fn
+ self.functors[ EnumToLong(funcType) ] = fn
return fn
## Return value of a functor for a given element
# with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
#
class meshProxy(SMESH._objref_SMESH_Mesh):
- def __init__(self):
- SMESH._objref_SMESH_Mesh.__init__(self)
+ def __init__(self, *args):
+ SMESH._objref_SMESH_Mesh.__init__(self, *args)
def __deepcopy__(self, memo=None):
- new = self.__class__()
+ new = self.__class__(self)
return new
def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
if len( args ) == 3:
## Private class wrapping SMESH.SMESH_SubMesh in order to add Compute()
#
class submeshProxy(SMESH._objref_SMESH_subMesh):
- def __init__(self):
- SMESH._objref_SMESH_subMesh.__init__(self)
+ def __init__(self, *args):
+ SMESH._objref_SMESH_subMesh.__init__(self, *args)
self.mesh = None
def __deepcopy__(self, memo=None):
- new = self.__class__()
+ new = self.__class__(self)
return new
## Compute the sub-mesh and return the status of the computation
ok = self.mesh.Compute( self.GetSubShape(),refresh=[] )
- if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
+ if salome.sg.hasDesktop():
smeshgui = salome.ImportComponentGUI("SMESH")
- smeshgui.Init(self.mesh.GetStudyId())
+ smeshgui.Init()
smeshgui.SetMeshIcon( salome.ObjectToID( self ), ok, (self.GetNumberOfElements()==0) )
- if refresh: salome.sg.updateObjBrowser(True)
+ if refresh: salome.sg.updateObjBrowser()
pass
return ok
# smeshBuilder.Mesh
#
class meshEditor(SMESH._objref_SMESH_MeshEditor):
- def __init__(self):
- SMESH._objref_SMESH_MeshEditor.__init__(self)
+ def __init__(self, *args):
+ SMESH._objref_SMESH_MeshEditor.__init__(self, *args)
self.mesh = None
def __getattr__(self, name ): # method called if an attribute not found
if not self.mesh: # look for name() method in Mesh class
return getattr( self.mesh, name )
if name == "ExtrusionAlongPathObjX":
return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
- print "meshEditor: attribute '%s' NOT FOUND" % name
+ print("meshEditor: attribute '%s' NOT FOUND" % name)
return None
def __deepcopy__(self, memo=None):
- new = self.__class__()
+ new = self.__class__(self)
return new
def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
if len( args ) == 1: args += False,
## Private class used to bind methods creating algorithms to the class Mesh
#
class algoCreator:
- def __init__(self):
+ def __init__(self, method):
self.mesh = None
self.defaultAlgoType = ""
self.algoTypeToClass = {}
+ self.method = method
# Store a python class of algorithm
def add(self, algoClass):
- if type( algoClass ).__name__ == 'classobj' and \
- hasattr( algoClass, "algoType"):
+ if inspect.isclass(algoClass) and \
+ hasattr(algoClass, "algoType"):
self.algoTypeToClass[ algoClass.algoType ] = algoClass
if not self.defaultAlgoType and \
hasattr( algoClass, "isDefault") and algoClass.isDefault:
# Create a copy of self and assign mesh to the copy
def copy(self, mesh):
- other = algoCreator()
+ other = algoCreator( self.method )
other.defaultAlgoType = self.defaultAlgoType
- other.algoTypeToClass = self.algoTypeToClass
+ other.algoTypeToClass = self.algoTypeToClass
other.mesh = mesh
return other
# Create an instance of algorithm
def __call__(self,algo="",geom=0,*args):
- algoType = self.defaultAlgoType
- for arg in args + (algo,geom):
- if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
- geom = arg
- if isinstance( arg, str ) and arg:
+ algoType = ""
+ shape = 0
+ if isinstance( algo, str ):
+ algoType = algo
+ elif ( isinstance( algo, geomBuilder.GEOM._objref_GEOM_Object ) and \
+ not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object )):
+ shape = algo
+ elif algo:
+ args += (algo,)
+
+ if isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
+ shape = geom
+ elif not algoType and isinstance( geom, str ):
+ algoType = geom
+ elif geom:
+ args += (geom,)
+ for arg in args:
+ if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ) and not shape:
+ shape = arg
+ elif isinstance( arg, str ) and not algoType:
algoType = arg
+ else:
+ import traceback, sys
+ msg = "Warning. Unexpected argument in mesh.%s() ---> %s" % ( self.method, arg )
+ sys.stderr.write( msg + '\n' )
+ tb = traceback.extract_stack(None,2)
+ traceback.print_list( [tb[0]] )
+ if not algoType:
+ algoType = self.defaultAlgoType
if not algoType and self.algoTypeToClass:
- algoType = self.algoTypeToClass.keys()[0]
- if self.algoTypeToClass.has_key( algoType ):
+ algoType = list(self.algoTypeToClass.keys())[0]
+ if algoType in self.algoTypeToClass:
#print "Create algo",algoType
- return self.algoTypeToClass[ algoType ]( self.mesh, geom )
- raise RuntimeError("No class found for algo type %s" % algoType)
++
+ return self.algoTypeToClass[ algoType ]( self.mesh, shape )
- raise RuntimeError, "No class found for algo type %s" % algoType
++ raise RuntimeError( "No class found for algo type %s" % algoType)
return None
## Private class used to substitute and store variable parameters of hypotheses.
except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
# maybe there is a replaced string arg which is not variable
result = self.method( self.hyp, *args )
- except ValueError, detail: # raised by ParseParameters()
+ except ValueError as detail: # raised by ParseParameters()
try:
result = self.method( self.hyp, *args )
except omniORB.CORBA.BAD_PARAM:
- raise ValueError, detail # wrong variable name
+ raise ValueError(detail) # wrong variable name
return result
pass
pluginBuilderName = pluginName + "Builder"
try:
exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
- except Exception, e:
- from salome_utils import verbose
- if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
+ except Exception as e:
+ from salome_utils import verbose
+ if verbose(): print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
continue
exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
plugin = eval( pluginBuilderName )
if k[0] == '_': continue
algo = getattr( plugin, k )
#print " algo:", str(algo)
- if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
+ if inspect.isclass(algo) and hasattr(algo, "meshMethod"):
#print " meshMethod:" , str(algo.meshMethod)
if not hasattr( Mesh, algo.meshMethod ):
- setattr( Mesh, algo.meshMethod, algoCreator() )
+ setattr( Mesh, algo.meshMethod, algoCreator( algo.meshMethod ))
pass
getattr( Mesh, algo.meshMethod ).add( algo )
pass
# Finds only the hypotheses created in smeshpyD engine.
# @return SMESH.SMESH_Hypothesis
def FindHypothesis (self, hypname, args, CompareMethod, smeshpyD):
- study = smeshpyD.GetCurrentStudy()
+ study = salome.myStudy
if not study: return None
#to do: find component by smeshpyD object, not by its data type
scomp = study.FindComponent(smeshpyD.ComponentDataType())
# Finds only the algorithms, which have been created in smeshpyD engine.
# @return SMESH.SMESH_Algo
def FindAlgorithm (self, algoname, smeshpyD):
- study = smeshpyD.GetCurrentStudy()
+ study = salome.myStudy
if not study: return None
#to do: find component by smeshpyD object, not by its data type
scomp = study.FindComponent(smeshpyD.ComponentDataType())
## Private method.
def Create(self, mesh, geom, hypo, so="libStdMeshersEngine.so"):
if geom is None and mesh.mesh.HasShapeToMesh():
- raise RuntimeError, "Attempt to create " + hypo + " algorithm on None shape"
+ raise RuntimeError("Attempt to create " + hypo + " algorithm on None shape")
algo = self.FindAlgorithm(hypo, mesh.smeshpyD)
if algo is None:
algo = mesh.smeshpyD.CreateHypothesis(hypo, so)
def Assign(self, algo, mesh, geom):
from salome.smesh.smeshBuilder import AssureGeomPublished, TreatHypoStatus, GetName
if geom is None and mesh.mesh.HasShapeToMesh():
- raise RuntimeError, "Attempt to create " + algo + " algorithm on None shape"
+ raise RuntimeError("Attempt to create " + algo + " algorithm on None shape")
self.mesh = mesh
if not geom or geom.IsSame( mesh.geom ):
self.geom = mesh.geom
return
def CompareHyp (self, hyp, args):
- print "CompareHyp is not implemented for ", self.__class__.__name__, ":", hyp.GetName()
+ print("CompareHyp is not implemented for ", self.__class__.__name__, ":", hyp.GetName())
return False
def CompareEqualHyp (self, hyp, args):
def ViscousLayers(self, thickness, numberOfLayers, stretchFactor,
faces=[], isFacesToIgnore=True, extrMethod=StdMeshers.SURF_OFFSET_SMOOTH ):
if not isinstance(self.algo, SMESH._objref_SMESH_3D_Algo):
- raise TypeError, "ViscousLayers are supported by 3D algorithms only"
+ raise TypeError("ViscousLayers are supported by 3D algorithms only")
if not "ViscousLayers" in self.GetCompatibleHypothesis():
- raise TypeError, "ViscousLayers are not supported by %s"%self.algo.GetName()
+ raise TypeError("ViscousLayers are not supported by %s"%self.algo.GetName())
if faces and isinstance( faces, geomBuilder.GEOM._objref_GEOM_Object ):
faces = [ faces ]
if faces and isinstance( faces[0], geomBuilder.GEOM._objref_GEOM_Object ):
def ViscousLayers2D(self, thickness, numberOfLayers, stretchFactor,
edges=[], isEdgesToIgnore=True ):
if not isinstance(self.algo, SMESH._objref_SMESH_2D_Algo):
- raise TypeError, "ViscousLayers2D are supported by 2D algorithms only"
+ raise TypeError("ViscousLayers2D are supported by 2D algorithms only")
if not "ViscousLayers2D" in self.GetCompatibleHypothesis():
- raise TypeError, "ViscousLayers2D are not supported by %s"%self.algo.GetName()
+ raise TypeError("ViscousLayers2D are not supported by %s"%self.algo.GetName())
if edges and not isinstance( edges, list ) and not isinstance( edges, tuple ):
edges = [edges]
if edges and isinstance( edges[0], geomBuilder.GEOM._objref_GEOM_Object ):
if isinstance( i, int ):
s = geompy.SubShapes(self.mesh.geom, [i])[0]
if s.GetShapeType() != geomBuilder.GEOM.EDGE:
- raise TypeError, "Not EDGE index given"
+ raise TypeError("Not EDGE index given")
resList.append( i )
elif isinstance( i, geomBuilder.GEOM._objref_GEOM_Object ):
if i.GetShapeType() != geomBuilder.GEOM.EDGE:
- raise TypeError, "Not an EDGE given"
+ raise TypeError("Not an EDGE given")
resList.append( geompy.GetSubShapeID(self.mesh.geom, i ))
elif len( i ) > 1:
e = i[0]
v = i[1]
if not isinstance( e, geomBuilder.GEOM._objref_GEOM_Object ) or \
not isinstance( v, geomBuilder.GEOM._objref_GEOM_Object ):
- raise TypeError, "A list item must be a tuple (edge, 1st_vertex_of_edge)"
+ raise TypeError("A list item must be a tuple (edge, 1st_vertex_of_edge)")
if v.GetShapeType() == geomBuilder.GEOM.EDGE and \
e.GetShapeType() == geomBuilder.GEOM.VERTEX:
v,e = e,v
if e.GetShapeType() != geomBuilder.GEOM.EDGE or \
v.GetShapeType() != geomBuilder.GEOM.VERTEX:
- raise TypeError, "A list item must be a tuple (edge, 1st_vertex_of_edge)"
+ raise TypeError("A list item must be a tuple (edge, 1st_vertex_of_edge)")
vFirst = FirstVertexOnCurve( self.mesh, e )
tol = geompy.Tolerance( vFirst )[-1]
if geompy.MinDistance( v, vFirst ) > 1.5*tol:
resList.append( geompy.GetSubShapeID(self.mesh.geom, e ))
else:
- raise TypeError, "Item must be either an edge or tuple (edge, 1st_vertex_of_edge)"
+ raise TypeError("Item must be either an edge or tuple (edge, 1st_vertex_of_edge)")
return resList
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import GEOM
# Converts swig to idl enumeration
def _swig2idl( type ):
- if _converter.has_key( type ) :
+ if type in _converter :
return _converter[type]
return None
# Check mesh parameter
entry = _getEntry(mesh)
if entry is None:
- print "Wrong 'mesh' parameter"
+ print("Wrong 'mesh' parameter")
return
# Check lst parameter
if isinstance( lst,list ) :
tmp = lst
else :
- print "Wrong 'lst' parameter"
+ print("Wrong 'lst' parameter")
return
sm_gui.select( entry, tmp, append )
def _preProcess(mesh) :
m = _getMesh(mesh);
if m is None:
- print "Wrong 'mesh' parameter"
+ print("Wrong 'mesh' parameter")
return [None, None]
elemType = _swig2idl(sm_gui.getSelectionMode())
SET(_link_LIBRARIES
${KERNEL_SalomeGenericObj}
${KERNEL_SALOMELocalTrace}
+ ${KERNEL_SalomeKernelHelpers}
${GUI_CAM}
${GUI_suit}
${GUI_qtx}
# swig flags
SET_SOURCE_FILES_PROPERTIES(libSMESH_Swig.i PROPERTIES CPLUSPLUS ON)
- SET_SOURCE_FILES_PROPERTIES(libSMESH_Swig.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+ SET_SOURCE_FILES_PROPERTIES(libSMESH_Swig.i PROPERTIES SWIG_FLAGS "-py3")
SET_SOURCE_FILES_PROPERTIES(libSMESH_swig_wrap.cpp PROPERTIES COMPILE_FLAGS "-DHAVE_CONFIG_H")
# --- scripts ---
SWIG_ADD_MODULE(libSMESH_Swig python ${SMESH_Swig_SOURCES})
SWIG_LINK_LIBRARIES(libSMESH_Swig ${_link_LIBRARIES})
+SWIG_CHECK_GENERATION(libSMESH_Swig)
IF(WIN32)
SET_TARGET_PROPERTIES(_libSMESH_Swig PROPERTIES DEBUG_OUTPUT_NAME _libSMESH_Swig_d)
ENDIF(WIN32)
import SMESH
from salome.kernel import studyedit
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
if not os.path.isfile(self.fichierOut):
QMessageBox.warning(self, "Compute", "Result file "+self.fichierOut+" not found")
- maStudy=studyedit.getActiveStudy()
- smesh.SetCurrentStudy(maStudy)
+ maStudy=salome.myStudy
(outputMesh, status) = smesh.CreateMeshesFromGMF(self.fichierOut)
name=str(self.LE_MeshSmesh.text())
initialMeshFile=None
newLink=monStudyBuilder.NewObject(SOMesh)
monStudyBuilder.Addreference(newLink, newStudyIter)
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num+=1
return True
#myStudy.IsStudyLocked()
myComponent = myStudy.FindComponent(name)
if myComponent == None:
- print "myComponent not found, create"
+ print("myComponent not found, create")
myComponent = myBuilder.NewComponent(name)
AName = myBuilder.FindOrCreateAttribute(myComponent, "AttributeName")
AName.SetValue(name)
ACmt = myBuilder.FindOrCreateAttribute(myObject, "AttributeComment")
ACmt.SetValue(datai)
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num += 1
- if verbose: print("save %s in Object Browser done: %s\n%s" % (name, myObject.GetID(), datai))
+ if verbose: print(("save %s in Object Browser done: %s\n%s" % (name, myObject.GetID(), datai)))
return True
def PBSaveHypPressed(self):
QMessageBox.warning(self, "Save", "waiting for fix: Object Browser will not display hypothesis")
if verbose: print("save hypothesis in Object Browser")
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
- maStudy=studyedit.getActiveStudy()
- smesh.SetCurrentStudy(maStudy)
+ maStudy=salome.myStudy
self.editor = studyedit.getStudyEditor()
moduleEntry=self.editor.findOrCreateComponent("SMESH","SMESH")
notebook.set("MGCleaner_%i" % self.num, data)
"""
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num += 1
- if verbose: print("save %s in Object Browser done:\n%s" % (name, data))
+ if verbose: print(("save %s in Object Browser done:\n%s" % (name, data)))
return True
def SP_toStr(self, widget):
if fd.exec_():
infile = fd.selectedFiles()[0]
self.LE_MeshFile.setText(infile)
- self.fichierIn=unicode(infile).encode("latin-1")
+ self.fichierIn=str(infile).encode("latin-1")
self.MeshIn=""
self.LE_MeshSmesh.setText("")
if fd.exec_():
infile = fd.selectedFiles()[0]
self.LE_ParamsFile.setText(infile)
- self.paramsFile=unicode(infile).encode("latin-1")
+ self.paramsFile=str(infile).encode("latin-1")
def meshFileNameChanged(self):
self.fichierIn=str(self.LE_MeshFile.text())
from salome.smesh.smeshstudytools import SMeshStudyTools
from salome.gui import helper as guihelper
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
mySObject, myEntry = guihelper.getSObjectSelected()
if CORBA.is_nil(mySObject) or mySObject==None:
if not self.CB_ComputedOverlapDistance.isChecked(): #computed default
self.commande+=" --overlap_distance " + self.SP_toStr(self.SP_OverlapDistance)
self.commande+=" --overlap_angle " + str(self.SP_OverlapAngle.value())
- if verbose: print("INFO: MGCCleaner command:\n %s" % self.commande)
+ if verbose: print(("INFO: MGCCleaner command:\n %s" % self.commande))
return True
def clean(self):
import SMESH
from salome.kernel import studyedit
salome.salome_init()
- maStudy=studyedit.getActiveStudy()
+ maStudy=salome.myStudy
#etc...a mano...
#
import math, Config
from salome.geom import geomBuilder
-geompy = geomBuilder.New( Config.theStudy )
+geompy = geomBuilder.New()
def Go(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish):
- """
- This function cuts any geometry (with infinite trim !) into several subgeometries that are cleanly saved inside the navigation tree. (Check GoTrim for the same functionality with custom trim size)
- - GeoObj is the geometrical object to be cut and grouped
- - CutPlnLst is a list of plane definitions. Each plane is a 6-tuple (contains 6 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane
- Example 1: [(0,0,0,1,0,0)]: cut along a plane passing through the origin and normal to the x-axis
- Example 2: [(0,0,0,1,0,0),(50,0,0,0,1,0)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis.
- Note that the plane size us determined automatically from the size of the geometry in question (using a very big trim size = 100 x length of geometry!)
- - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
- A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
- A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
- The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
- Example 1: [1]
- Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
- - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
- Example 1: ['Entry']
- Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
-
- Imagine that we have a solid called ExampleSolid, an example command will be:
- CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0),(50,0,0,0,1,0)],[1, 2],['Entry','Exit'])
- """
-
- NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 1)
- OrigType = FindStandType(GeoObj,0)
- InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
- TrimSize = geompy.BasicProperties(GeoObj)[0]*100
- CutPlane = [] ; Sections = [] ; Parts = []
-
- if NumCuts:
- for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
- CutPlane.append(CreatePlane(CutPlnLst[i],TrimSize))
- OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
- if Publish: geompy.addToStudy(OutFather,'SectionedObject')
- for i in range(0, NumCuts):
- for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
- if j == 8 : j = 7; # Exception for the vertex case (=7)
- PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
- PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
- Accepted = []
- for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane! if yes add them to current list
- if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7):
- Accepted.append(PossSubShapesID[k])
- if Accepted : # If some element is found, save it as a group with the prescribed Prefix
- dummyObj = geompy.CreateGroup(OutFather, j)
- geompy.UnionIDs(dummyObj, Accepted)
- Sections.append(dummyObj)
- if Publish:geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
- else :
- print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created"
-
- SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
- for i in range(0,len(SubShapesID)):
- dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
- geompy.UnionIDs(dummyObj, [SubShapesID[i]])
- Parts.append(dummyObj)
- if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
-
- return OutFather, Sections, Parts
- else:
- print("Fatal error, the routine cannot continue any further, check your input variables")
- return -1
+ """
+ This function cuts any geometry (with infinite trim !) into several subgeometries that are cleanly saved inside the navigation tree. (Check GoTrim for the same functionality with custom trim size)
+ - GeoObj is the geometrical object to be cut and grouped
+ - CutPlnLst is a list of plane definitions. Each plane is a 6-tuple (contains 6 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane
+ Example 1: [(0,0,0,1,0,0)]: cut along a plane passing through the origin and normal to the x-axis
+ Example 2: [(0,0,0,1,0,0),(50,0,0,0,1,0)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis.
+ Note that the plane size us determined automatically from the size of the geometry in question (using a very big trim size = 100 x length of geometry!)
+ - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
+ A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
+ A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
+ The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
+ Example 1: [1]
+ Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
+ - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
+ Example 1: ['Entry']
+ Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
+
+ Imagine that we have a solid called ExampleSolid, an example command will be:
+ CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0),(50,0,0,0,1,0)],[1, 2],['Entry','Exit'])
+ """
+
+ NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 1)
+ OrigType = FindStandType(GeoObj,0)
+ InvDictionary = {v: k for k, v in geompy.ShapeType.items()} # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
+ TrimSize = geompy.BasicProperties(GeoObj)[0]*100
+ CutPlane = [] ; Sections = [] ; Parts = []
+
+ if NumCuts:
+ for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
+ CutPlane.append(CreatePlane(CutPlnLst[i],TrimSize))
+ OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
+ if Publish: geompy.addToStudy(OutFather,'SectionedObject')
+ for i in range(0, NumCuts):
+ for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
+ if j == 8 : j = 7; # Exception for the vertex case (=7)
+ PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
+ PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
+ Accepted = []
+ for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane! if yes add them to current list
+ if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7):
+ Accepted.append(PossSubShapesID[k])
+ if Accepted : # If some element is found, save it as a group with the prescribed Prefix
+ dummyObj = geompy.CreateGroup(OutFather, j)
+ geompy.UnionIDs(dummyObj, Accepted)
+ Sections.append(dummyObj)
+ if Publish:geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
+ else :
+ print("Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created")
+
+ SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
+ for i in range(0,len(SubShapesID)):
+ dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
+ geompy.UnionIDs(dummyObj, [SubShapesID[i]])
+ Parts.append(dummyObj)
+ if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
+
+ return OutFather, Sections, Parts
+ else:
+ print("Fatal error, the routine cannot continue any further, check your input variables")
+ return -1
def GoTrim(GeoObj, CutPlnLst, OutLvlLst, PrefixLst, Publish):
- """
- This function cuts any geometry into several subgeometries that are cleanly saved inside the navigation tree with a fully customizable trim size.
- - GeoObj is the geometrical object to be cut and grouped
- - CutPlnLst is a list of plane definitions. Each plane is a 7-tuple (contains 7 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane, the last value corresponds to the trim size of the planes
- Example 1: [(0,0,0,1,0,0,5)]: cut along a plane passing through the origin and normal to the x-axis with a trim size of 5
- Example 2: [(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis with a trim size of 10
- - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
- A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
- A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
- The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
- Example 1: [1]
- Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
- - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
- Example 1: ['Entry']
- Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
-
- Imagine that we have a solid called ExampleSolid, an example command will be:
- CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)],[1, 2],['Entry','Exit'])
- """
-
- NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 0)
- OrigType = FindStandType(GeoObj,0)
- InvDictionary = dict((v,k) for k, v in geompy.ShapeType.iteritems()) # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
- CutPlane = [] ; Sections = [] ; Parts = []
- if NumCuts:
- for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
- CutPlane.append(CreatePlane(CutPlnLst[i][0:6],CutPlnLst[i][6]))
- OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
- if Publish: geompy.addToStudy(OutFather,'SectionedObject')
- for i in range(0, NumCuts):
- for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
- if j == 8 : j = 7; # Exception for the vertex case (=7)
- PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
- PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
- Accepted = []
- for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane WITH THE TRIM SIZE CONDITION! if yes add them to current list
- if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7) and Distance2Pt(geompy.PointCoordinates(geompy.MakeCDG(PossSubShapes[k])),CutPlnLst[i][0:3])<=CutPlnLst[i][-1]:
- Accepted.append(PossSubShapesID[k])
- if Accepted : # If some element is found, save it as a group with the prescribed Prefix
- dummyObj = geompy.CreateGroup(OutFather, j)
- geompy.UnionIDs(dummyObj, Accepted)
- Sections.append(dummyObj)
- if Publish: geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
- else :
- print "Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created"
-
- SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
- for i in range(0,len(SubShapesID)):
- dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
- geompy.UnionIDs(dummyObj, [SubShapesID[i]])
- Parts.append(dummyObj)
- if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
-
- return OutFather, Sections, Parts
- else:
- print("Fatal error, the routine cannot continue any further, check your input variables")
- return -1
+ """
+ This function cuts any geometry into several subgeometries that are cleanly saved inside the navigation tree with a fully customizable trim size.
+ - GeoObj is the geometrical object to be cut and grouped
+ - CutPlnLst is a list of plane definitions. Each plane is a 7-tuple (contains 7 values). The first three represent the coordinates of the origin point and the second three represent the coordinates of the normal vector to the plane, the last value corresponds to the trim size of the planes
+ Example 1: [(0,0,0,1,0,0,5)]: cut along a plane passing through the origin and normal to the x-axis with a trim size of 5
+ Example 2: [(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)]: in addition to the first plane cut, cut through a plane passing by (50,0,0) and normal to the y axis with a trim size of 10
+ - OutLvlLst is a list containing integers that represent the inner sectioning level with respect to the original geometry type
+ A value of 1 means that the section will provide elements of one level lower than the original type. For example a solid sectioned at level 1 will produce faces. A Face sectioned at level 1 will produce edges.
+ A value of 2 means that a deeper sectioning will be applied. A solid sectioned with level 2 will give faces and edges. A face will give edges and vertices. An edge will give only vertices
+ The number of elements in this list should be (this is verified in the code) equal to the number of elements in the plane cut list. This is logical.
+ Example 1: [1]
+ Example 2: [1, 2], This means that the cut over the second plane will produce two types of elements unlike the first cut which will only output the first level objects.
+ - PrefixLst is a list of strings that contains the naming Prefixes that are used by the script to generate the subshape names. This is very useful for relating the results to the sectioning requested.
+ Example 1: ['Entry']
+ Example 2: ['Entry','Exit'] The resulting groups from the sectioning with plane no.1 will then be saved as "Entry_FACE" and/or "Entry_EDGE" according to the original geometry object type and the cutting level
+
+ Imagine that we have a solid called ExampleSolid, an example command will be:
+ CutnGroup.Go(ExampleSolid,[(0,0,0,1,0,0,5),(50,0,0,0,1,0,10)],[1, 2],['Entry','Exit'])
+ """
+
+ NumCuts = CheckInput(CutPlnLst, OutLvlLst, PrefixLst, 0)
+ OrigType = FindStandType(GeoObj,0)
+ InvDictionary = {v: k for k, v in geompy.ShapeType.items()} # Give geometry type name as a function of standard type numbering, ex: 4=FACE, 6=EDGE, 7=VERTEX
+ CutPlane = [] ; Sections = [] ; Parts = []
+ if NumCuts:
+ for i in range(0, NumCuts): # Loop over the cutting planes to create them one by one
+ CutPlane.append(CreatePlane(CutPlnLst[i][0:6],CutPlnLst[i][6]))
+ OutFather = geompy.MakePartition([GeoObj],CutPlane, [], [],FindStandType(GeoObj,1), 0, [], 0) #Creating the partition object
+ if Publish: geompy.addToStudy(OutFather,'SectionedObject')
+ for i in range(0, NumCuts):
+ for j in range(OrigType+1+2, OrigType+1+2*(OutLvlLst[i]+1),2):
+ if j == 8 : j = 7; # Exception for the vertex case (=7)
+ PossSubShapesID = geompy.SubShapeAllIDs(OutFather,j) # List of subshape IDs than correspond to the required cutting level (section type : face/wire/vertex)
+ PossSubShapes = geompy.ExtractShapes(OutFather,j) # and the corresponding objects
+ Accepted = []
+ for k in range(0,len(PossSubShapesID)): # Loop over all the subshapes checking if they belong to the cutting plane WITH THE TRIM SIZE CONDITION! if yes add them to current list
+ if IsOnPlane(PossSubShapes[k], CutPlnLst[i], 1e-7) and Distance2Pt(geompy.PointCoordinates(geompy.MakeCDG(PossSubShapes[k])),CutPlnLst[i][0:3])<=CutPlnLst[i][-1]:
+ Accepted.append(PossSubShapesID[k])
+ if Accepted : # If some element is found, save it as a group with the prescribed Prefix
+ dummyObj = geompy.CreateGroup(OutFather, j)
+ geompy.UnionIDs(dummyObj, Accepted)
+ Sections.append(dummyObj)
+ if Publish: geompy.addToStudyInFather(OutFather, dummyObj, PrefixLst[i]+"_"+InvDictionary[j][0:2])
+ else :
+ print("Warning: For the section no.", i, ", No intersection of type " + InvDictionary[j] + " was found. Hence, no corresponding groups were created")
+
+ SubShapesID = geompy.SubShapeAllIDs(OutFather,OrigType+1) # Saving also the groups corresponding to the sectioned item of the same type: ex. A solid into n sub-solids due to the sections
+ for i in range(0,len(SubShapesID)):
+ dummyObj = geompy.CreateGroup(OutFather, OrigType+1)
+ geompy.UnionIDs(dummyObj, [SubShapesID[i]])
+ Parts.append(dummyObj)
+ if Publish: geompy.addToStudyInFather(OutFather, dummyObj, "SB"+"_"+InvDictionary[OrigType+1][0:3]+"_"+str(i+1))
+
+ return OutFather, Sections, Parts
+ else:
+ print("Fatal error, the routine cannot continue any further, check your input variables")
+ return -1
def FindStandType(GeoObj, method):
- """
- Find the standard index for the Geometrical object/compound type input, see dictionary in geompy.ShapeType
- """
- TopType = GeoObj.GetMaxShapeType().__str__()
- UnModType = geompy.ShapeType[TopType]
- if method == 0 :
- StandType = UnModType-int(not(UnModType%2)) # So that wires and edges and considered the same, faces and shells, and so on
- else :
- StandType = UnModType
-
- return(StandType)
+ """
+ Find the standard index for the Geometrical object/compound type input, see dictionary in geompy.ShapeType
+ """
+ TopType = GeoObj.GetMaxShapeType().__str__()
+ UnModType = geompy.ShapeType[TopType]
+ if method == 0 :
+ StandType = UnModType-int(not(UnModType%2)) # So that wires and edges and considered the same, faces and shells, and so on
+ else :
+ StandType = UnModType
+
+ return(StandType)
def CreatePlane(CutPlnVar,Trim):
- """
- Creates a temporary point and vector in salome in order to build the sectioning planes needed
- """
- Temp_Vtx = geompy.MakeVertex(CutPlnVar[0], CutPlnVar[1], CutPlnVar[2])
- Temp_Vec = geompy.MakeVectorDXDYDZ(CutPlnVar[3], CutPlnVar[4], CutPlnVar[5])
- CutPlane = geompy.MakePlane(Temp_Vtx, Temp_Vec, Trim)
- return(CutPlane)
+ """
+ Creates a temporary point and vector in salome in order to build the sectioning planes needed
+ """
+ Temp_Vtx = geompy.MakeVertex(CutPlnVar[0], CutPlnVar[1], CutPlnVar[2])
+ Temp_Vec = geompy.MakeVectorDXDYDZ(CutPlnVar[3], CutPlnVar[4], CutPlnVar[5])
+ CutPlane = geompy.MakePlane(Temp_Vtx, Temp_Vec, Trim)
+ return(CutPlane)
def CheckInput(CutPlnLst, OutLvlLst, PrefixLst, AutoTrim):
- """
- Checks the user input specifically if all needed parameters are provided
- """
- if not ((len(CutPlnLst) == len(OutLvlLst)) and (len(CutPlnLst) == len(PrefixLst))):
- print("Missing information about one or more of the cut planes")
- return 0
- elif not ((len(CutPlnLst[0]) == 6+int(not AutoTrim))):
- print("For each cutting plane you need to specify 6 parameters = 2 x 3 coordinates")
- return 0
- else:
- return len(CutPlnLst)
+ """
+ Checks the user input specifically if all needed parameters are provided
+ """
+ if not ((len(CutPlnLst) == len(OutLvlLst)) and (len(CutPlnLst) == len(PrefixLst))):
+ print("Missing information about one or more of the cut planes")
+ return 0
+ elif not ((len(CutPlnLst[0]) == 6+int(not AutoTrim))):
+ print("For each cutting plane you need to specify 6 parameters = 2 x 3 coordinates")
+ return 0
+ else:
+ return len(CutPlnLst)
def IsOnPlane(GeoSubObj, CutPlnVar, tolerance):
- """
- Checks whether a geometry (vertex, segment, or face) belongs *completely* to the plane defined as a point and a normal vector
- """
- # lambda function that represents the plane equation, function = 0 <=> Pt defined with Coor belongs to plane
- PlaneEq = lambda Coor: CutPlnVar[3]*(Coor[0]-CutPlnVar[0])+CutPlnVar[4]*(Coor[1]-CutPlnVar[1])+CutPlnVar[5]*(Coor[2]-CutPlnVar[2])
- OrigType = FindStandType(GeoSubObj,0)
- if (OrigType >= 7): # Vertex
- NonTrimDecision = abs(PlaneEq(geompy.PointCoordinates(GeoSubObj))) < tolerance
- if len(CutPlnVar) == 6 : return NonTrimDecision # No trim condition used
- else : return (NonTrimDecision and Distance2Pt(CutPlnVar[0:3],geompy.PointCoordinates(GeoSubObj))<=CutPlnVar[6]/2)
- elif (OrigType >= 5): # Line, decompose into two points then call recursively IsOnPlane function!
- Verdict = True
- for i in range(0,2):
- Verdict = Verdict and IsOnPlane(geompy.GetVertexByIndex(GeoSubObj,i), CutPlnVar, tolerance)
- return Verdict
- elif (OrigType >= 3): # Face, decompose into three points then call recursively IsOnPlane function!
- if IsOnPlane(geompy.MakeCDG(GeoSubObj),CutPlnVar, tolerance) : # Center of gravity belongs to plane, check if normal is parallel to plane
- NormalP1Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),0))
- NormalP2Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),1))
- Normal = [NormalP1Coor[0]-NormalP2Coor[0], NormalP1Coor[1]-NormalP2Coor[1], NormalP1Coor[2]-NormalP2Coor[2]]
- CrossP = CrossProd(CutPlnVar[3:6],Normal) # Checks whether normals (of section plane and of face) are parallel or not
- if (abs(CrossP[0])<tolerance and abs(CrossP[1])<tolerance and abs(CrossP[2])<tolerance): # meaning zero cross product => parallel
- return True
- else :
- return False
- else :
- return False
+ """
+ Checks whether a geometry (vertex, segment, or face) belongs *completely* to the plane defined as a point and a normal vector
+ """
+ # lambda function that represents the plane equation, function = 0 <=> Pt defined with Coor belongs to plane
+ PlaneEq = lambda Coor: CutPlnVar[3]*(Coor[0]-CutPlnVar[0])+CutPlnVar[4]*(Coor[1]-CutPlnVar[1])+CutPlnVar[5]*(Coor[2]-CutPlnVar[2])
+ OrigType = FindStandType(GeoSubObj,0)
+ if (OrigType >= 7): # Vertex
+ NonTrimDecision = abs(PlaneEq(geompy.PointCoordinates(GeoSubObj))) < tolerance
+ if len(CutPlnVar) == 6 : return NonTrimDecision # No trim condition used
+ else : return (NonTrimDecision and Distance2Pt(CutPlnVar[0:3],geompy.PointCoordinates(GeoSubObj))<=CutPlnVar[6]/2)
+ elif (OrigType >= 5): # Line, decompose into two points then call recursively IsOnPlane function!
+ Verdict = True
+ for i in range(0,2):
+ Verdict = Verdict and IsOnPlane(geompy.GetVertexByIndex(GeoSubObj,i), CutPlnVar, tolerance)
+ return Verdict
+ elif (OrigType >= 3): # Face, decompose into three points then call recursively IsOnPlane function!
+ if IsOnPlane(geompy.MakeCDG(GeoSubObj),CutPlnVar, tolerance) : # Center of gravity belongs to plane, check if normal is parallel to plane
+ NormalP1Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),0))
+ NormalP2Coor = geompy.PointCoordinates(geompy.GetVertexByIndex(geompy.GetNormal(GeoSubObj),1))
+ Normal = [NormalP1Coor[0]-NormalP2Coor[0], NormalP1Coor[1]-NormalP2Coor[1], NormalP1Coor[2]-NormalP2Coor[2]]
+ CrossP = CrossProd(CutPlnVar[3:6],Normal) # Checks whether normals (of section plane and of face) are parallel or not
+ if (abs(CrossP[0])<tolerance and abs(CrossP[1])<tolerance and abs(CrossP[2])<tolerance): # meaning zero cross product => parallel
+ return True
+ else :
+ return False
+ else :
+ return False
def CrossProd(V1,V2):
- """
- Determines the cross product of two 3D vectors
- """
- return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]])
+ """
+ Determines the cross product of two 3D vectors
+ """
+ return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]])
def Distance2Pt(P1,P2):
- """
- Returns the distance between two points
- """
- return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2))
+ """
+ Returns the distance between two points
+ """
+ return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2))
import CompositeBox
from salome.geom import geomBuilder
-geompy = geomBuilder.New( Config.theStudy )
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New( Config.theStudy )
+smesh = smeshBuilder.New()
##########################################################################################################
def Box11 (MacObject):
- if Config.debug : print "Generating regular box"
+ if Config.debug : print("Generating regular box")
- dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+ dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
- Reg1D = MacObject.Mesh[0].Segment()
- Reg1D.NumberOfSegments(MacObject.MeshPar[0])
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.DirectionalMeshParams = [MacObject.MeshPar[0],MacObject.MeshPar[0],MacObject.MeshPar[0],MacObject.MeshPar[0]]
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+ Reg1D = MacObject.Mesh[0].Segment()
+ Reg1D.NumberOfSegments(MacObject.MeshPar[0])
- MacObject.status = 1
- Config.ListObj.append(MacObject)
- return MacObject
+ MacObject.Mesh[0].Compute() # Generates the mesh
+
+ MacObject.DirectionalMeshParams = [MacObject.MeshPar[0],MacObject.MeshPar[0],MacObject.MeshPar[0],MacObject.MeshPar[0]]
+
+ MacObject.status = 1
+ Config.ListObj.append(MacObject)
+ return MacObject
##########################################################################################################
def Box42 (MacObject):
- if Config.debug : print "Generating box 4-2 reducer"
+ if Config.debug : print("Generating box 4-2 reducer")
+
+ Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
+ RotAngle = {'SN' : lambda : 0,
+ 'NS' : lambda : math.pi,
+ 'EW' : lambda : math.pi/2,
+ 'WE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
+ dummy0 = geompy.MakeRotation( ElemBox42 () , Z_Axis, RotAngle )
+ dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
- Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
- RotAngle = {'SN' : lambda : 0,
- 'NS' : lambda : math.pi,
- 'EW' : lambda : math.pi/2,
- 'WE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
- dummy0 = geompy.MakeRotation( ElemBox42 () , Z_Axis, RotAngle )
- dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
- Reg1D = MacObject.Mesh[0].Segment()
- Reg1D.NumberOfSegments(MacObject.MeshPar[0])
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+ Reg1D = MacObject.Mesh[0].Segment()
+ Reg1D.NumberOfSegments(MacObject.MeshPar[0])
- MacObject.Mesh[0].Compute() # Generates the mesh
+ MacObject.Mesh[0].Compute() # Generates the mesh
- MacObject.status = 1
+ MacObject.status = 1
- x = MacObject.MeshPar[0]
- MacObject.DirectionalMeshParams = {'SN' : lambda : [3*x, 3*x, 4*x, 2*x],
- 'NS' : lambda : [3*x, 3*x, 2*x, 4*x],
- 'EW' : lambda : [2*x, 4*x, 3*x, 3*x],
- 'WE' : lambda : [4*x, 2*x, 3*x, 3*x], }[MacObject.MeshPar[1]]()
+ x = MacObject.MeshPar[0]
+ MacObject.DirectionalMeshParams = {'SN' : lambda : [3*x, 3*x, 4*x, 2*x],
+ 'NS' : lambda : [3*x, 3*x, 2*x, 4*x],
+ 'EW' : lambda : [2*x, 4*x, 3*x, 3*x],
+ 'WE' : lambda : [4*x, 2*x, 3*x, 3*x], }[MacObject.MeshPar[1]]()
+
+ Config.ListObj.append(MacObject)
+ return MacObject
- Config.ListObj.append(MacObject)
- return MacObject
-
##########################################################################################################
def BoxAng32 (MacObject):
- if Config.debug : print "Generating sharp angle"
- Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
- RotAngle = {'NE' : lambda : 0,
- 'NW' : lambda : math.pi/2,
- 'SW' : lambda : math.pi,
- 'SE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
- dummy0 = geompy.MakeRotation( ElemEdge32 () , Z_Axis, RotAngle )
- dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
-
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
-
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
-
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
- Reg1D = MacObject.Mesh[0].Segment()
- Reg1D.NumberOfSegments(MacObject.MeshPar[0])
-
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.status = 1
-
- x = MacObject.MeshPar[0]
- MacObject.DirectionalMeshParams = {'NE' : lambda : [3*x, 2*x, 3*x, 2*x],
- 'NW' : lambda : [2*x, 3*x, 3*x, 2*x],
- 'SW' : lambda : [2*x, 3*x, 2*x, 3*x],
- 'SE' : lambda : [3*x, 2*x, 2*x, 3*x], }[MacObject.MeshPar[1]]()
-
- Config.ListObj.append(MacObject)
- return MacObject
+ if Config.debug : print("Generating sharp angle")
+ Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
+ RotAngle = {'NE' : lambda : 0,
+ 'NW' : lambda : math.pi/2,
+ 'SW' : lambda : math.pi,
+ 'SE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
+ dummy0 = geompy.MakeRotation( ElemEdge32 () , Z_Axis, RotAngle )
+ dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
+
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+ Reg1D = MacObject.Mesh[0].Segment()
+ Reg1D.NumberOfSegments(MacObject.MeshPar[0])
+
+ MacObject.Mesh[0].Compute() # Generates the mesh
+
+ MacObject.status = 1
+
+ x = MacObject.MeshPar[0]
+ MacObject.DirectionalMeshParams = {'NE' : lambda : [3*x, 2*x, 3*x, 2*x],
+ 'NW' : lambda : [2*x, 3*x, 3*x, 2*x],
+ 'SW' : lambda : [2*x, 3*x, 2*x, 3*x],
+ 'SE' : lambda : [3*x, 2*x, 2*x, 3*x], }[MacObject.MeshPar[1]]()
+
+ Config.ListObj.append(MacObject)
+ return MacObject
##########################################################################################################
def CompBox (MacObject):
- if Config.debug : print "Generating composite box"
+ if Config.debug : print("Generating composite box")
+
+ dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
- dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
- ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
+ ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
- Reference = [0,0,0]
- Vec = [(1,0,0),(0,1,0)]
- for Edge in EdgeIDs:
- for i in range(0,2):
- if IsParallel(Edge,Vec[i]):
- if not Reference[i]: # If this is the first found edge to be parallel to this direction, apply user preferences for meshing
- Reference[i] = Edge
- ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(ReducedRatio[i]*MacObject.MeshPar[0])))
- break
- else: # If there already exists an edge parallel to this direction, then use a 1D projection
- Apply1DProjMesh(MacObject.Mesh[0],Edge,Reference[i])
- break
+ Reference = [0,0,0]
+ Vec = [(1,0,0),(0,1,0)]
+ for Edge in EdgeIDs:
+ for i in range(0,2):
+ if IsParallel(Edge,Vec[i]):
+ if not Reference[i]: # If this is the first found edge to be parallel to this direction, apply user preferences for meshing
+ Reference[i] = Edge
+ ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(ReducedRatio[i]*MacObject.MeshPar[0])))
+ break
+ else: # If there already exists an edge parallel to this direction, then use a 1D projection
+ Apply1DProjMesh(MacObject.Mesh[0],Edge,Reference[i])
+ break
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.DirectionalMeshParams = [MacObject.MeshPar[0]*ReducedRatio[1],MacObject.MeshPar[0]*ReducedRatio[1],MacObject.MeshPar[0]*ReducedRatio[0],MacObject.MeshPar[0]*ReducedRatio[0]]
+ MacObject.Mesh[0].Compute() # Generates the mesh
- MacObject.status = 1
- Config.ListObj.append(MacObject)
- return MacObject
+ MacObject.DirectionalMeshParams = [MacObject.MeshPar[0]*ReducedRatio[1],MacObject.MeshPar[0]*ReducedRatio[1],MacObject.MeshPar[0]*ReducedRatio[0],MacObject.MeshPar[0]*ReducedRatio[0]]
+
+ MacObject.status = 1
+ Config.ListObj.append(MacObject)
+ return MacObject
##########################################################################################################
def CompBoxF (MacObject):
- if Config.debug : print "Generating composite box"
-
- dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
-
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
-
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
-
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
-
- #ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
-
- Reference = [0,0,0]
- Vec = [(1,0,0),(0,1,0)]
- for Edge in EdgeIDs:
- for i in range(0,2):
- if IsParallel(Edge,Vec[i]):
- if not Reference[i]: # If this is the first found edge to be parallel to this direction, apply user preferences for meshing
- Reference[i] = Edge
- ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(MacObject.MeshPar[0][i])))
- break
- else: # If there already exists an edge parallel to this direction, then use a 1D projection
- Apply1DProjMesh(MacObject.Mesh[0],Edge,Reference[i])
- break
-
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.DirectionalMeshParams = [MacObject.MeshPar[0][1],MacObject.MeshPar[0][1],MacObject.MeshPar[0][0],MacObject.MeshPar[0][0]]
-
- MacObject.status = 1
- Config.ListObj.append(MacObject)
- return MacObject
+ if Config.debug : print("Generating composite box")
+
+ dummy1 = geompy.MakeScaleAlongAxes( ElemBox11 (), None , MacObject.GeoPar[1][0], MacObject.GeoPar[1][1], 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
+
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+
+ #ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
+
+ Reference = [0,0,0]
+ Vec = [(1,0,0),(0,1,0)]
+ for Edge in EdgeIDs:
+ for i in range(0,2):
+ if IsParallel(Edge,Vec[i]):
+ if not Reference[i]: # If this is the first found edge to be parallel to this direction, apply user preferences for meshing
+ Reference[i] = Edge
+ ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(MacObject.MeshPar[0][i])))
+ break
+ else: # If there already exists an edge parallel to this direction, then use a 1D projection
+ Apply1DProjMesh(MacObject.Mesh[0],Edge,Reference[i])
+ break
+
+ MacObject.Mesh[0].Compute() # Generates the mesh
+
+ MacObject.DirectionalMeshParams = [MacObject.MeshPar[0][1],MacObject.MeshPar[0][1],MacObject.MeshPar[0][0],MacObject.MeshPar[0][0]]
+
+ MacObject.status = 1
+ Config.ListObj.append(MacObject)
+ return MacObject
##########################################################################################################
def NonOrtho (MacObject):
- if Config.debug : print "Generating Non-orthogonal quadrangle"
-
- RectFace = Quadrangler (MacObject.PtCoor)
-
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Quad_"+ str(len(Config.ListObj)+1))
-
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
-
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
-
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
-
- #ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
-
- Vec = [MacObject.DirVectors(i) for i in range(4)]
- for Edge in EdgeIDs:
- Dir = [IsParallel(Edge,Vec[j]) for j in range(4)].index(True)
- DirConv = [0,0,1,1][Dir]
- ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(MacObject.MeshPar[0][DirConv])))
-
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.DirectionalMeshParams = [MacObject.MeshPar[0][1],MacObject.MeshPar[0][1],MacObject.MeshPar[0][0],MacObject.MeshPar[0][0]]
-
- MacObject.status = 1
- Config.ListObj.append(MacObject)
- return MacObject
+ if Config.debug : print("Generating Non-orthogonal quadrangle")
+
+ RectFace = Quadrangler (MacObject.PtCoor)
+
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Quad_"+ str(len(Config.ListObj)+1))
+
+
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+
+ #ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0],MacObject.GeoPar[1][1])
+
+ Vec = [MacObject.DirVectors(i) for i in range(4)]
+ for Edge in EdgeIDs:
+ Dir = [IsParallel(Edge,Vec[j]) for j in range(4)].index(True)
+ DirConv = [0,0,1,1][Dir]
+ ApplyConstant1DMesh(MacObject.Mesh[0],Edge,int(round(MacObject.MeshPar[0][DirConv])))
+
+ MacObject.Mesh[0].Compute() # Generates the mesh
+
+ MacObject.DirectionalMeshParams = [MacObject.MeshPar[0][1],MacObject.MeshPar[0][1],MacObject.MeshPar[0][0],MacObject.MeshPar[0][0]]
+
+ MacObject.status = 1
+ Config.ListObj.append(MacObject)
+ return MacObject
##########################################################################################################
def QuartCyl (MacObject):
- if Config.debug : print "Generating quarter cylinder"
- Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
- RotAngle = {'NE' : lambda : 0,
- 'NW' : lambda : math.pi/2,
- 'SW' : lambda : math.pi,
- 'SE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
- dummy0 = geompy.MakeRotation( ElemQuartCyl(MacObject.MeshPar[2]) , Z_Axis, RotAngle )
- dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0]/10., MacObject.GeoPar[1][1]/10., 1)
- RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
-
- MacObject.GeoChildren.append(RectFace)
- MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
-
- if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
-
- if Config.publish :
- MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
- Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
-
- EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
- Reg1D = MacObject.Mesh[0].Segment()
-
- #if MacObject.MeshPar[0] == 2 and MacObject.MeshPar[2] <= 2.:
- # print("Due to a bug in Salome 6.3, we are forced to either increase or decrease the local refinement by 50%, we choose in this case to increase the model's refinement.")
- # MacObject.MeshPar[0] = 3
-
- Reg1D.NumberOfSegments(MacObject.MeshPar[0])
-
- MacObject.Mesh[0].Compute() # Generates the mesh
-
- MacObject.status = 1
-
- x = MacObject.MeshPar[0]
- N = QuarCylParam(MacObject.MeshPar[2])+1
-
- MacObject.DirectionalMeshParams = {'NE' : lambda : [2*x, N*x, 2*x, N*x],
- 'NW' : lambda : [N*x, 2*x, 2*x, N*x],
- 'SW' : lambda : [N*x, 2*x, N*x, 2*x],
- 'SE' : lambda : [2*x, N*x, N*x, 2*x], }[MacObject.MeshPar[1]]()
-
- Config.ListObj.append(MacObject)
- return MacObject
-
+ if Config.debug : print("Generating quarter cylinder")
+ Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
+ RotAngle = {'NE' : lambda : 0,
+ 'NW' : lambda : math.pi/2,
+ 'SW' : lambda : math.pi,
+ 'SE' : lambda : -math.pi/2, }[MacObject.MeshPar[1]]()
+ dummy0 = geompy.MakeRotation( ElemQuartCyl(MacObject.MeshPar[2]) , Z_Axis, RotAngle )
+ dummy1 = geompy.MakeScaleAlongAxes( dummy0, None , MacObject.GeoPar[1][0]/10., MacObject.GeoPar[1][1]/10., 1)
+ RectFace = geompy.MakeTranslation(dummy1, MacObject.GeoPar[0][0], MacObject.GeoPar[0][1], 0)
+
+ MacObject.GeoChildren.append(RectFace)
+ MacObject.GeoChildrenNames.append("Box_"+ str(len(Config.ListObj)+1))
+
+ if Config.debug : Publish (MacObject.GeoChildren,MacObject.GeoChildrenNames)
+
+ if Config.publish :
+ MacObject.Mesh.append(smesh.Mesh(RectFace)) # Creation of a new mesh
+ Quad2D = MacObject.Mesh[0].Quadrangle() # Applying a quadrangle hypothesis
+
+ EdgeIDs = geompy.SubShapeAllSorted(RectFace,6) # List of Edge IDs belonging to RectFace, 6 = Edge in salome dictionary
+ Reg1D = MacObject.Mesh[0].Segment()
+
+ #if MacObject.MeshPar[0] == 2 and MacObject.MeshPar[2] <= 2.:
+ # print("Due to a bug in Salome 6.3, we are forced to either increase or decrease the local refinement by 50%, we choose in this case to increase the model's refinement.")
+ # MacObject.MeshPar[0] = 3
+
+ Reg1D.NumberOfSegments(MacObject.MeshPar[0])
+
+ MacObject.Mesh[0].Compute() # Generates the mesh
+
+ MacObject.status = 1
+
+ x = MacObject.MeshPar[0]
+ N = QuarCylParam(MacObject.MeshPar[2])+1
+
+ MacObject.DirectionalMeshParams = {'NE' : lambda : [2*x, N*x, 2*x, N*x],
+ 'NW' : lambda : [N*x, 2*x, 2*x, N*x],
+ 'SW' : lambda : [N*x, 2*x, N*x, 2*x],
+ 'SE' : lambda : [2*x, N*x, N*x, 2*x], }[MacObject.MeshPar[1]]()
+
+ Config.ListObj.append(MacObject)
+ return MacObject
+
##########################################################################################################
- # Below this are the elementary calculation/visualization functions
+ # Below this are the elementary calculation/visualization functions
##########################################################################################################
def Publish (ObjToPublish,NamesToPublish):
- i = 0
- for GeoObj in ObjToPublish :
- geompy.addToStudy(GeoObj,NamesToPublish[i])
- i = i+1
+ i = 0
+ for GeoObj in ObjToPublish :
+ geompy.addToStudy(GeoObj,NamesToPublish[i])
+ i = i+1
def IsParallel (Edge, Vector):
- """
- Function checks whether a given edge object is parallel to a reference vector.
- Output can be 0 (not parallel) or 1 (parallel and same sense) or 2 (parallel and opposite sense).
- If the reference vector is null, the function returns 0
- """
- if Vector == (0,0,0) : return 0
- else :
- P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
- P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
- V0 = [ P1[0] - P2[0], P1[1] - P2[1], P1[2] - P2[2] ]
- if Distance2Pt((0,0,0),CrossProd(V0,Vector))<1e-7 and DotProd(V0,Vector) > 0 : return 1
- elif Distance2Pt((0,0,0),CrossProd(V0,Vector))<1e-7 and DotProd(V0,Vector) < 0 : return 2
- else : return 0
+ """
+ Function checks whether a given edge object is parallel to a reference vector.
+ Output can be 0 (not parallel) or 1 (parallel and same sense) or 2 (parallel and opposite sense).
+ If the reference vector is null, the function returns 0
+ """
+ if Vector == (0,0,0) : return 0
+ else :
+ P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
+ P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
+ V0 = [ P1[0] - P2[0], P1[1] - P2[1], P1[2] - P2[2] ]
+ if Distance2Pt((0,0,0),CrossProd(V0,Vector))<1e-7 and DotProd(V0,Vector) > 0 : return 1
+ elif Distance2Pt((0,0,0),CrossProd(V0,Vector))<1e-7 and DotProd(V0,Vector) < 0 : return 2
+ else : return 0
def IsOnCircle (Edge, Center, Radius):
- """
- Function checks whether a given edge object belong to the periphery of a circle defined by its
- center and radius.
- Output can be 0 (does not belong) or 1 (belongs).
- If the reference Radius is null, the function returns 0
- Note that this function is basic in the sense that it only checks if the two border points of a
- given edge belong to the arc of reference.
- """
- if Radius == 0 : return 0
- else :
- P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
- P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
- if abs(Distance2Pt(Center,P1)-Radius) < 1e-6 and abs(Distance2Pt(Center,P2)-Radius) < 1e-6:
- return 1
- else :
- return 0
-
+ """
+ Function checks whether a given edge object belong to the periphery of a circle defined by its
+ center and radius.
+ Output can be 0 (does not belong) or 1 (belongs).
+ If the reference Radius is null, the function returns 0
+ Note that this function is basic in the sense that it only checks if the two border points of a
+ given edge belong to the arc of reference.
+ """
+ if Radius == 0 : return 0
+ else :
+ P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
+ P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
+ if abs(Distance2Pt(Center,P1)-Radius) < 1e-6 and abs(Distance2Pt(Center,P2)-Radius) < 1e-6:
+ return 1
+ else :
+ return 0
+
def CrossProd(V1,V2):
- """
- Determines the cross product of two 3D vectors
- """
- return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]])
+ """
+ Determines the cross product of two 3D vectors
+ """
+ return ([V1[1]*V2[2]-V1[2]*V2[1], V1[2]*V2[0]-V1[0]*V2[2], V1[0]*V2[1]-V1[1]*V2[0]])
def QuarCylParam(PitchRatio):
- R = float(PitchRatio)/(PitchRatio+1)
- Eps = 1. - R
- X = (R+Eps/2.)*math.sin(math.pi/4)+Eps/2.
- N = int(math.floor((math.pi*R/4.)/(Eps/2.)))
- return N
+ R = float(PitchRatio)/(PitchRatio+1)
+ Eps = 1. - R
+ X = (R+Eps/2.)*math.sin(math.pi/4)+Eps/2.
+ N = int(math.floor((math.pi*R/4.)/(Eps/2.)))
+ return N
def DotProd(V1,V2):
- """
- Determines the dot product of two 3D vectors
- """
- if len(V1)==2 : V1.append(0)
- if len(V2)==2 : V2.append(0)
-
- return (V1[0]*V2[0]+V1[1]*V2[1]+V1[2]*V2[2])
+ """
+ Determines the dot product of two 3D vectors
+ """
+ if len(V1)==2 : V1.append(0)
+ if len(V2)==2 : V2.append(0)
+
+ return (V1[0]*V2[0]+V1[1]*V2[1]+V1[2]*V2[2])
def Distance2Pt(P1,P2):
- """
- Returns the distance between two points
- """
- return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2))
+ """
+ Returns the distance between two points
+ """
+ return (math.sqrt((P1[0]-P2[0])**2+(P1[1]-P2[1])**2+(P1[2]-P2[2])**2))
def ApplyConstant1DMesh (ParentMsh, Edge, Nseg):
- Reg1D = ParentMsh.Segment(geom=Edge)
- Len = Reg1D.NumberOfSegments(Nseg)
+ Reg1D = ParentMsh.Segment(geom=Edge)
+ Len = Reg1D.NumberOfSegments(Nseg)
def Apply1DProjMesh (ParentMsh, Edge, Ref):
- Proj1D = ParentMsh.Projection1D(geom=Edge)
- SrcEdge = Proj1D.SourceEdge(Ref,None,None,None)
+ Proj1D = ParentMsh.Projection1D(geom=Edge)
+ SrcEdge = Proj1D.SourceEdge(Ref,None,None,None)
def EdgeLength (Edge):
- """
- This function returns the edge object length.
- """
- P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
- P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
- return Distance2Pt(P1,P2)
+ """
+ This function returns the edge object length.
+ """
+ P1 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,0))
+ P2 = geompy.PointCoordinates(geompy.GetVertexByIndex(Edge,1))
+ return Distance2Pt(P1,P2)
def D2R (Angle):
- return Angle*math.pi/180
+ return Angle*math.pi/180
def R2D (Angle):
- return Angle*180/math.pi
+ return Angle*180/math.pi
def F2D (FloatNumber):
- return round(FloatNumber*100.)/100.
+ return round(FloatNumber*100.)/100.
def BezierGen (PointA, PointB, AngleA, AngleB):
- if AngleA == 0 and AngleB == 0 : return (geompy.MakeEdge(PointA, PointB))
- else :
- A = geompy.PointCoordinates(PointA)
- B = geompy.PointCoordinates(PointB)
- dAB = Distance2Pt(A,B)
- dAC = dAB * (math.tan(AngleA)*math.tan(AngleB)) / (math.sin(AngleA) * ( math.tan(AngleA)+math.tan(AngleB) ) )
- AngleOX_AB = math.acos((B[0]-A[0])/dAB)
- PointC = geompy.MakeVertex(A[0]+math.cos(AngleA+AngleOX_AB)*dAC,A[1]+math.sin(AngleA+AngleOX_AB)*dAC,0)
- CurveACB = geompy.MakeBezier([PointA,PointC,PointB])
- return CurveACB
+ if AngleA == 0 and AngleB == 0 : return (geompy.MakeEdge(PointA, PointB))
+ else :
+ A = geompy.PointCoordinates(PointA)
+ B = geompy.PointCoordinates(PointB)
+ dAB = Distance2Pt(A,B)
+ dAC = dAB * (math.tan(AngleA)*math.tan(AngleB)) / (math.sin(AngleA) * ( math.tan(AngleA)+math.tan(AngleB) ) )
+ AngleOX_AB = math.acos((B[0]-A[0])/dAB)
+ PointC = geompy.MakeVertex(A[0]+math.cos(AngleA+AngleOX_AB)*dAC,A[1]+math.sin(AngleA+AngleOX_AB)*dAC,0)
+ CurveACB = geompy.MakeBezier([PointA,PointC,PointB])
+ return CurveACB
def GetSideAngleForBezier (PointA , PointB):
- """
- This function takes for input two points A and B where the bezier line is needed. It calculates the incident
- angle needed at point A so that the final curve is either at 0 or 90 degrees from the x'Ox axis
- """
- A = geompy.PointCoordinates(PointA)
- B = geompy.PointCoordinates(PointB)
- ABx = B[0]-A[0]
- dAB = Distance2Pt(A,B)
- Alpha = math.acos(ABx/dAB)
- #print "New angle request"
- #print ABx, dAB, R2D(Alpha)
- if Alpha < math.pi/4 :
- #print "returning", R2D(-Alpha)
- return -Alpha
- elif Alpha < 3*math.pi/4 :
- #print "returning", R2D(-(Alpha-math.pi/2))
- return -(Alpha-math.pi/2)
- else :
- #print "returning", R2D(-(Alpha-math.pi))
- return -(Alpha-math.pi)
+ """
+ This function takes for input two points A and B where the bezier line is needed. It calculates the incident
+ angle needed at point A so that the final curve is either at 0 or 90 degrees from the x'Ox axis
+ """
+ A = geompy.PointCoordinates(PointA)
+ B = geompy.PointCoordinates(PointB)
+ ABx = B[0]-A[0]
+ dAB = Distance2Pt(A,B)
+ Alpha = math.acos(ABx/dAB)
+ #print "New angle request"
+ #print ABx, dAB, R2D(Alpha)
+ if Alpha < math.pi/4 :
+ #print "returning", R2D(-Alpha)
+ return -Alpha
+ elif Alpha < 3*math.pi/4 :
+ #print "returning", R2D(-(Alpha-math.pi/2))
+ return -(Alpha-math.pi/2)
+ else :
+ #print "returning", R2D(-(Alpha-math.pi))
+ return -(Alpha-math.pi)
def VecDivRatio (Vec1, Vec2):
- """
- This function tries to find the ratio of Vec1 on Vec2 while neglecting any zero term in Vec1. This is used afterwards
- for determining the global mesh parameter from automatically detected directional mesh params. If no compatibility is
- possible, the function returns -1
- """
- Vec3 = []
- for i in range(len(Vec1)) :
- Vec3.append(float(Vec1[i])/Vec2[i])
- Ratio=[]
- for i in Vec3 :
- if not (abs(i)<1e-7) : Ratio.append(i)
- if Ratio :
- if min(Ratio) == max(Ratio) and min(Ratio)==int(min(Ratio)) : return(min(Ratio))
- else : return -1
- else :
- return -2
-
-
+ """
+ This function tries to find the ratio of Vec1 on Vec2 while neglecting any zero term in Vec1. This is used afterwards
+ for determining the global mesh parameter from automatically detected directional mesh params. If no compatibility is
+ possible, the function returns -1
+ """
+ Vec3 = []
+ for i in range(len(Vec1)) :
+ Vec3.append(float(Vec1[i])/Vec2[i])
+ Ratio=[]
+ for i in Vec3 :
+ if not (abs(i)<1e-7) : Ratio.append(i)
+ if Ratio :
+ if min(Ratio) == max(Ratio) and min(Ratio)==int(min(Ratio)) : return(min(Ratio))
+ else : return -1
+ else :
+ return -2
+
+
def ReduceRatio (dx, dy):
- """
- This function transforms a decimal ratio into a scale between two integers, for example : [0.2,0.05] --> [4,1] ;
- """
- Output = [0,0]
- ratio = float(dy)/dx
- if isinteger(ratio) : return [1,ratio]
- elif dx == 1 : # when this function is called recursively!
- for i in range(1,20) : # searches over 20 decimals
- if isinteger(ratio * (10**i) ) :
- Output = GetScale((10**i),int(round(ratio * (10**i) ) ) )
- break
- else :
- for n in range(0,i) :
- if isinteger(ratio * ( 10**(i)-10**(n) )) :
- Output = GetScale( 10**(i)-10**(n) , int(round(ratio * ( 10**(i)-10**(n) ) ) ) )
- break
- if not (Output==[0,0]) : break
- return Output
- else :
- for i in range(1,10) : # searches over 10 decimals
- if isinteger(ratio * (10**i) ) :
- Output = GetScale((10**i),int(round(ratio * (10**i) ) ) )
- break
- else :
- for n in range(0,i) :
- if isinteger(ratio * ( 10**(i)-10**(n) )) :
- Output = GetScale( 10**(i)-10**(n) , int(round(ratio * ( 10**(i)-10**(n) ) ) ) )
- break
- if not (Output==[0,0]) : break
-
- if Output == [0,0] :
- print "We are having some trouble while interpreting the following ratio: ",ratio, "\nWe will try a recursive method which may in some cases take some time..."
- if dy > dx :
- A = ReduceRatio (dx, dy-dx)
- return ([A[0],A[1]+A[0]])
- else :
- A = ReduceRatio (dy, dx-dy)
- return ([A[1]+A[0],A[0]])
-
- else : return Output
-
+ """
+ This function transforms a decimal ratio into a scale between two integers, for example : [0.2,0.05] --> [4,1] ;
+ """
+ Output = [0,0]
+ ratio = float(dy)/dx
+ if isinteger(ratio) : return [1,ratio]
+ elif dx == 1 : # when this function is called recursively!
+ for i in range(1,20) : # searches over 20 decimals
+ if isinteger(ratio * (10**i) ) :
+ Output = GetScale((10**i),int(round(ratio * (10**i) ) ) )
+ break
+ else :
+ for n in range(0,i) :
+ if isinteger(ratio * ( 10**(i)-10**(n) )) :
+ Output = GetScale( 10**(i)-10**(n) , int(round(ratio * ( 10**(i)-10**(n) ) ) ) )
+ break
+ if not (Output==[0,0]) : break
+ return Output
+ else :
+ for i in range(1,10) : # searches over 10 decimals
+ if isinteger(ratio * (10**i) ) :
+ Output = GetScale((10**i),int(round(ratio * (10**i) ) ) )
+ break
+ else :
+ for n in range(0,i) :
+ if isinteger(ratio * ( 10**(i)-10**(n) )) :
+ Output = GetScale( 10**(i)-10**(n) , int(round(ratio * ( 10**(i)-10**(n) ) ) ) )
+ break
+ if not (Output==[0,0]) : break
+
+ if Output == [0,0] :
+ print("We are having some trouble while interpreting the following ratio: ",ratio, "\nWe will try a recursive method which may in some cases take some time...")
+ if dy > dx :
+ A = ReduceRatio (dx, dy-dx)
+ return ([A[0],A[1]+A[0]])
+ else :
+ A = ReduceRatio (dy, dx-dy)
+ return ([A[1]+A[0],A[0]])
+
+ else : return Output
+
def GetScale (X,Y):
- """
- This function is called within ReduceRatio and aims to reduce down two integers X and Y by dividing them with their common divisors;
- Example: 25 and 5 ---> 5 and 1 / 63 and 12 ---> 21 and 4
- """
- MaxDiv = max(X,Y)
- Divisor = 2 # Initializing the divisor
- while MaxDiv >= Divisor :
- X0 = 0
- Y0 = 0
- if not(X%Divisor) :
- X0 = X/Divisor
- MaxDiv = max(MaxDiv,X0)
- if not(Y%Divisor) :
- Y0 = Y/Divisor
- MaxDiv = max(MaxDiv,Y0)
- if (X0*Y0) :
- X = X0
- Y = Y0
- else :
- Divisor = Divisor + 1
- return [X,Y]
+ """
+ This function is called within ReduceRatio and aims to reduce down two integers X and Y by dividing them with their common divisors;
+ Example: 25 and 5 ---> 5 and 1 / 63 and 12 ---> 21 and 4
+ """
+ MaxDiv = max(X,Y)
+ Divisor = 2 # Initializing the divisor
+ while MaxDiv >= Divisor :
+ X0 = 0
+ Y0 = 0
+ if not(X%Divisor) :
+ X0 = X/Divisor
+ MaxDiv = max(MaxDiv,X0)
+ if not(Y%Divisor) :
+ Y0 = Y/Divisor
+ MaxDiv = max(MaxDiv,Y0)
+ if (X0*Y0) :
+ X = X0
+ Y = Y0
+ else :
+ Divisor = Divisor + 1
+ return [X,Y]
def isinteger (x) :
- """
- This functions applies a simple check if the entered value is an integer
- """
- x = float('%.5f' % (x)) #Truncate x to 5 digits after the decimal point
- if math.ceil(x) == math.floor(x) : return True
- else : return False
+ """
+ This functions applies a simple check if the entered value is an integer
+ """
+ x = float('%.5f' % (x)) #Truncate x to 5 digits after the decimal point
+ if math.ceil(x) == math.floor(x) : return True
+ else : return False
##########################################################################################
# Below this are the functions that create the elementary forms for the macro objects
##########################################################################################
def ElemBox11 ():
- """
- This function returns a simple square face of 1 side length
- """
- RectFace = geompy.MakeFaceHW(1, 1, 1)
- return RectFace
+ """
+ This function returns a simple square face of 1 side length
+ """
+ RectFace = geompy.MakeFaceHW(1, 1, 1)
+ return RectFace
def ElemBox42 ():
- """
- This function returns a square face of 1 side length, partitioned
- according to the elementary 4 to 2 reductor method
- """
- OrigRectFace = geompy.MakeFaceHW(1, 1, 1)
-
- SouthPt1 = geompy.MakeVertex (-.25, -.5, 0)
- SouthPt2 = geompy.MakeVertex (0, -.5, 0)
- SouthPt3 = geompy.MakeVertex (.25, -.5, 0)
- WestPt1 = geompy.MakeVertex (-.5, -.5+1./3, 0)
- WestPt2 = geompy.MakeVertex (-.5, -.5+2./3, 0)
- EastPt1 = geompy.MakeVertex (.5, -.5+1./3, 0)
- EastPt2 = geompy.MakeVertex (.5, -.5+2./3, 0)
- NorthPt = geompy.MakeVertex (0, .5, 0)
- MidPt1 = geompy.MakeVertex (0, .05, 0)
- MidPt2 = geompy.MakeVertex (.2, -.18, 0)
- MidPt3 = geompy.MakeVertex (0, -.28, 0)
- MidPt4 = geompy.MakeVertex (-.2, -.18, 0)
-
- Cutter = []
- Cutter.append(geompy.MakeEdge(SouthPt2, MidPt3))
- Cutter.append(geompy.MakeEdge(MidPt1, NorthPt))
- Cutter.append(BezierGen(SouthPt1, MidPt4, GetSideAngleForBezier(SouthPt1,MidPt4), D2R(15)))
- Cutter.append(BezierGen(SouthPt3, MidPt2, GetSideAngleForBezier(SouthPt3,MidPt2), D2R(-15)))
- Cutter.append(BezierGen(WestPt1, MidPt4, GetSideAngleForBezier(WestPt1,MidPt4), D2R(-10)))
- Cutter.append(BezierGen(EastPt1, MidPt2, GetSideAngleForBezier(EastPt1,MidPt2), D2R(10)))
- Cutter.append(BezierGen(WestPt2, MidPt1, GetSideAngleForBezier(WestPt2,MidPt1), D2R(-10)))
- Cutter.append(BezierGen(EastPt2, MidPt1, GetSideAngleForBezier(EastPt2,MidPt1), D2R(10)))
- Cutter.append(BezierGen(MidPt2, MidPt1, D2R(-15), D2R(-15)))
- Cutter.append(BezierGen(MidPt3, MidPt2, D2R(10), D2R(15)))
- Cutter.append(BezierGen(MidPt3, MidPt4, D2R(-10), D2R(-15)))
- Cutter.append(BezierGen(MidPt4, MidPt1, D2R(15), D2R(15)))
-
- RectFace = geompy.MakePartition([OrigRectFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
- #i=1
- #for SingleCut in Cutter :
- # geompy.addToStudy(SingleCut,'Cutter'+str(i))
- # i = i+1
- #geompy.addToStudy(RectFace,'RectFace')
- return RectFace
+ """
+ This function returns a square face of 1 side length, partitioned
+ according to the elementary 4 to 2 reductor method
+ """
+ OrigRectFace = geompy.MakeFaceHW(1, 1, 1)
+
+ SouthPt1 = geompy.MakeVertex (-.25, -.5, 0)
+ SouthPt2 = geompy.MakeVertex (0, -.5, 0)
+ SouthPt3 = geompy.MakeVertex (.25, -.5, 0)
+ WestPt1 = geompy.MakeVertex (-.5, -.5+1./3, 0)
+ WestPt2 = geompy.MakeVertex (-.5, -.5+2./3, 0)
+ EastPt1 = geompy.MakeVertex (.5, -.5+1./3, 0)
+ EastPt2 = geompy.MakeVertex (.5, -.5+2./3, 0)
+ NorthPt = geompy.MakeVertex (0, .5, 0)
+ MidPt1 = geompy.MakeVertex (0, .05, 0)
+ MidPt2 = geompy.MakeVertex (.2, -.18, 0)
+ MidPt3 = geompy.MakeVertex (0, -.28, 0)
+ MidPt4 = geompy.MakeVertex (-.2, -.18, 0)
+
+ Cutter = []
+ Cutter.append(geompy.MakeEdge(SouthPt2, MidPt3))
+ Cutter.append(geompy.MakeEdge(MidPt1, NorthPt))
+ Cutter.append(BezierGen(SouthPt1, MidPt4, GetSideAngleForBezier(SouthPt1,MidPt4), D2R(15)))
+ Cutter.append(BezierGen(SouthPt3, MidPt2, GetSideAngleForBezier(SouthPt3,MidPt2), D2R(-15)))
+ Cutter.append(BezierGen(WestPt1, MidPt4, GetSideAngleForBezier(WestPt1,MidPt4), D2R(-10)))
+ Cutter.append(BezierGen(EastPt1, MidPt2, GetSideAngleForBezier(EastPt1,MidPt2), D2R(10)))
+ Cutter.append(BezierGen(WestPt2, MidPt1, GetSideAngleForBezier(WestPt2,MidPt1), D2R(-10)))
+ Cutter.append(BezierGen(EastPt2, MidPt1, GetSideAngleForBezier(EastPt2,MidPt1), D2R(10)))
+ Cutter.append(BezierGen(MidPt2, MidPt1, D2R(-15), D2R(-15)))
+ Cutter.append(BezierGen(MidPt3, MidPt2, D2R(10), D2R(15)))
+ Cutter.append(BezierGen(MidPt3, MidPt4, D2R(-10), D2R(-15)))
+ Cutter.append(BezierGen(MidPt4, MidPt1, D2R(15), D2R(15)))
+
+ RectFace = geompy.MakePartition([OrigRectFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
+ #i=1
+ #for SingleCut in Cutter :
+ # geompy.addToStudy(SingleCut,'Cutter'+str(i))
+ # i = i+1
+ #geompy.addToStudy(RectFace,'RectFace')
+ return RectFace
def ElemEdge32 ():
- """
- This function returns a square face of 1 side length, partitioned
- according to the elementary edge with 3 to 2 reductor
- """
- OrigRectFace = geompy.MakeFaceHW(1., 1., 1)
-
- SouthPt1 = geompy.MakeVertex (-1./6, -0.5, 0.)
- SouthPt2 = geompy.MakeVertex ( 1./6, -0.5, 0.)
- WestPt1 = geompy.MakeVertex (-0.5, -1./6, 0.)
- WestPt2 = geompy.MakeVertex (-0.5, 1./6, 0.)
- EastPt = geompy.MakeVertex ( 0.5, 0., 0.)
- NorthPt = geompy.MakeVertex (0., 0.5, 0.)
-
- MidPt1 = geompy.MakeVertex (-0.2, -0.2, 0.)
- MidPt2 = geompy.MakeVertex ( -0.02, -0.02, 0.)
-
- Cutter = []
- Cutter.append(BezierGen(SouthPt1, MidPt1, GetSideAngleForBezier(SouthPt1,MidPt1) , D2R(-5)))
- Cutter.append(BezierGen( WestPt1, MidPt1, GetSideAngleForBezier(WestPt1 ,MidPt1) , D2R(-5)))
- Cutter.append(BezierGen(SouthPt2, MidPt2, GetSideAngleForBezier(SouthPt2,MidPt2) , D2R(-10)))
- Cutter.append(BezierGen( EastPt, MidPt2, GetSideAngleForBezier(EastPt ,MidPt2) , D2R(5)))
- Cutter.append(BezierGen( WestPt2, MidPt2, GetSideAngleForBezier(WestPt2 ,MidPt2) , D2R(-10)))
- Cutter.append(BezierGen( MidPt2, NorthPt, GetSideAngleForBezier(NorthPt ,MidPt2) , D2R(-5)))
-
- Cutter.append(geompy.MakeEdge(MidPt1, MidPt2))
-
- RectFace = geompy.MakePartition([OrigRectFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
- #i=1
- #for SingleCut in Cutter :
- # geompy.addToStudy(SingleCut,'Cutter'+str(i))
- # i = i+1
- #geompy.addToStudy(RectFace,'RectFace')
- return RectFace
+ """
+ This function returns a square face of 1 side length, partitioned
+ according to the elementary edge with 3 to 2 reductor
+ """
+ OrigRectFace = geompy.MakeFaceHW(1., 1., 1)
+
+ SouthPt1 = geompy.MakeVertex (-1./6, -0.5, 0.)
+ SouthPt2 = geompy.MakeVertex ( 1./6, -0.5, 0.)
+ WestPt1 = geompy.MakeVertex (-0.5, -1./6, 0.)
+ WestPt2 = geompy.MakeVertex (-0.5, 1./6, 0.)
+ EastPt = geompy.MakeVertex ( 0.5, 0., 0.)
+ NorthPt = geompy.MakeVertex (0., 0.5, 0.)
+
+ MidPt1 = geompy.MakeVertex (-0.2, -0.2, 0.)
+ MidPt2 = geompy.MakeVertex ( -0.02, -0.02, 0.)
+
+ Cutter = []
+ Cutter.append(BezierGen(SouthPt1, MidPt1, GetSideAngleForBezier(SouthPt1,MidPt1) , D2R(-5)))
+ Cutter.append(BezierGen( WestPt1, MidPt1, GetSideAngleForBezier(WestPt1 ,MidPt1) , D2R(-5)))
+ Cutter.append(BezierGen(SouthPt2, MidPt2, GetSideAngleForBezier(SouthPt2,MidPt2) , D2R(-10)))
+ Cutter.append(BezierGen( EastPt, MidPt2, GetSideAngleForBezier(EastPt ,MidPt2) , D2R(5)))
+ Cutter.append(BezierGen( WestPt2, MidPt2, GetSideAngleForBezier(WestPt2 ,MidPt2) , D2R(-10)))
+ Cutter.append(BezierGen( MidPt2, NorthPt, GetSideAngleForBezier(NorthPt ,MidPt2) , D2R(-5)))
+
+ Cutter.append(geompy.MakeEdge(MidPt1, MidPt2))
+
+ RectFace = geompy.MakePartition([OrigRectFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
+ #i=1
+ #for SingleCut in Cutter :
+ # geompy.addToStudy(SingleCut,'Cutter'+str(i))
+ # i = i+1
+ #geompy.addToStudy(RectFace,'RectFace')
+ return RectFace
def Quadrangler (Points):
- """
- This function returns a quadranglar face based on four points, non of which 3 are non-colinear.
- The points are defined by their 2D [(x1,y1),(x2,y2)..] coordinates.
- Note that the list of points is already arranged upon the creation in MacObject
- """
- Pt = []
- for Point in Points: Pt.append(geompy.MakeVertex(Point[0], Point[1], 0))
- # The first point is added at the end of the list in order to facilitate the line creation
- Pt.append(Pt[0])
- #Draw the lines in order to form the 4 side polygon
- Ln=[]
- for i in range(4) : Ln.append(geompy.MakeLineTwoPnt(Pt[i],Pt[i+1]))
- RectFace = geompy.MakeQuad (Ln[0],Ln[1],Ln[2],Ln[3])
- return RectFace
+ """
+ This function returns a quadranglar face based on four points, non of which 3 are non-colinear.
+ The points are defined by their 2D [(x1,y1),(x2,y2)..] coordinates.
+ Note that the list of points is already arranged upon the creation in MacObject
+ """
+ Pt = []
+ for Point in Points: Pt.append(geompy.MakeVertex(Point[0], Point[1], 0))
+ # The first point is added at the end of the list in order to facilitate the line creation
+ Pt.append(Pt[0])
+ #Draw the lines in order to form the 4 side polygon
+ Ln=[]
+ for i in range(4) : Ln.append(geompy.MakeLineTwoPnt(Pt[i],Pt[i+1]))
+ RectFace = geompy.MakeQuad (Ln[0],Ln[1],Ln[2],Ln[3])
+ return RectFace
def ElemQuartCyl(K):
- """
- This function returns a quarter cylinder to box relay of 1 side length, partitioned
- with a pitch ratio of K, In other words the side of the box is R*(1+(1/K))
- """
- R = 10.*float(K)/(K+1)
- Eps = 10.- R
-
- Config.theStudy.SetReal("R" , R)
- Config.theStudy.SetReal("minusR" , -R)
- Config.theStudy.SetReal("Eps", Eps)
-
- CylWire = geompy.MakeSketcher("Sketcher:F 'R' 0:R 0:L 'Eps':TT 10. 10.0:R 90:L 10.0:R 90:L 'Eps':R 90:C 'minusR' 90.0:WW", [0, 0, 0, 0, 0, 1, 1, 0, -0])
- CylFace = geompy.MakeFace(CylWire, 1)
-
- SouthPt = geompy.MakeVertex (R+Eps/2., 0., 0)
- SouthWestPt = geompy.MakeVertex ( 0.,0., 0) #The origin can be used for practical partionning objectifs
- WestPt = geompy.MakeVertex (0., R+Eps/2., 0)
-
- N = int(math.floor((math.pi*R/4.)/(Eps/2.)))
- X = 10.*(1.-1./(N+1))
-
-
- EastPt = geompy.MakeVertex (10.0, X, 0.)
- NorthPt = geompy.MakeVertex ( X, 10.0, 0.)
-
- DivFactor = 8./(F2D(math.log(K))-0.223)
- #MidPt = geompy.MakeVertex ((R+Eps)*math.cos(math.pi/4), (R+Eps)*math.sin(math.pi/4), 0.)
- MidPt = geompy.MakeVertex (X-Eps/DivFactor, X-Eps/DivFactor, 0.)
-
- Cutter = []
- Cutter.append(BezierGen(SouthWestPt, MidPt, GetSideAngleForBezier(SouthWestPt,MidPt) , D2R(-5)))
- Cutter.append(BezierGen( EastPt, MidPt, GetSideAngleForBezier(EastPt,MidPt) , D2R(5)))
- Cutter.append(BezierGen( MidPt, NorthPt, (-1)**((K<1.25)*1)*D2R(-5), GetSideAngleForBezier(NorthPt,MidPt)))
- SMBezier = BezierGen( SouthPt, MidPt, GetSideAngleForBezier(SouthPt ,MidPt) , D2R((K<1.25)*180-5))
- WMBezier = BezierGen( WestPt, MidPt, GetSideAngleForBezier(WestPt, MidPt) , D2R(-5))
- Cutter.append(WMBezier)
- Cutter.append(SMBezier)
-
- for i in range(1,N) :
- # Determining intermediate points on the bezier lines and then performing additional cuts
-
- TempAnglePlus = (math.pi/4)*(1+float(i)/N)
- SectionResult = CutnGroup.Go(WMBezier, [(0,0,0,math.sin(TempAnglePlus),-math.cos(TempAnglePlus),0)], [1], ['Dummy'], 0)
- TempPt1 = SectionResult[1][0]
- TempPt11 = geompy.MakeVertex ((N-i)*X/N, 10., 0)
-
- TempAngleMinus = (math.pi/4)*(1-float(i)/N)
- SectionResult = CutnGroup.Go(SMBezier, [(0,0,0,math.sin(TempAngleMinus),-math.cos(TempAngleMinus),0)], [1], ['Dummy'], 0)
- TempPt2 = SectionResult[1][0]
- TempPt21 = geompy.MakeVertex (10., (N-i)*X/N, 0)
-
- Cutter.append(geompy.MakeEdge(SouthWestPt, TempPt1))
- Cutter.append(geompy.MakeEdge(SouthWestPt, TempPt2))
- Cutter.append(geompy.MakeEdge(TempPt1, TempPt11))
- Cutter.append(geompy.MakeEdge(TempPt2, TempPt21))
-
- CylFace = geompy.MakePartition([CylFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
- CylFace = geompy.MakeTranslation(CylFace, -5., -5., 0.0)
-
- return CylFace
-
+ """
+ This function returns a quarter cylinder to box relay of 1 side length, partitioned
+ with a pitch ratio of K, In other words the side of the box is R*(1+(1/K))
+ """
+ R = 10.*float(K)/(K+1)
+ Eps = 10.- R
+
+ Config.theStudy.SetReal("R" , R)
+ Config.theStudy.SetReal("minusR" , -R)
+ Config.theStudy.SetReal("Eps", Eps)
+
+ CylWire = geompy.MakeSketcher("Sketcher:F 'R' 0:R 0:L 'Eps':TT 10. 10.0:R 90:L 10.0:R 90:L 'Eps':R 90:C 'minusR' 90.0:WW", [0, 0, 0, 0, 0, 1, 1, 0, -0])
+ CylFace = geompy.MakeFace(CylWire, 1)
+
+ SouthPt = geompy.MakeVertex (R+Eps/2., 0., 0)
+ SouthWestPt = geompy.MakeVertex ( 0.,0., 0) #The origin can be used for practical partionning objectifs
+ WestPt = geompy.MakeVertex (0., R+Eps/2., 0)
+
+ N = int(math.floor((math.pi*R/4.)/(Eps/2.)))
+ X = 10.*(1.-1./(N+1))
+
+
+ EastPt = geompy.MakeVertex (10.0, X, 0.)
+ NorthPt = geompy.MakeVertex ( X, 10.0, 0.)
+
+ DivFactor = 8./(F2D(math.log(K))-0.223)
+ #MidPt = geompy.MakeVertex ((R+Eps)*math.cos(math.pi/4), (R+Eps)*math.sin(math.pi/4), 0.)
+ MidPt = geompy.MakeVertex (X-Eps/DivFactor, X-Eps/DivFactor, 0.)
+
+ Cutter = []
+ Cutter.append(BezierGen(SouthWestPt, MidPt, GetSideAngleForBezier(SouthWestPt,MidPt) , D2R(-5)))
+ Cutter.append(BezierGen( EastPt, MidPt, GetSideAngleForBezier(EastPt,MidPt) , D2R(5)))
+ Cutter.append(BezierGen( MidPt, NorthPt, (-1)**((K<1.25)*1)*D2R(-5), GetSideAngleForBezier(NorthPt,MidPt)))
+ SMBezier = BezierGen( SouthPt, MidPt, GetSideAngleForBezier(SouthPt ,MidPt) , D2R((K<1.25)*180-5))
+ WMBezier = BezierGen( WestPt, MidPt, GetSideAngleForBezier(WestPt, MidPt) , D2R(-5))
+ Cutter.append(WMBezier)
+ Cutter.append(SMBezier)
+
+ for i in range(1,N) :
+ # Determining intermediate points on the bezier lines and then performing additional cuts
+
+ TempAnglePlus = (math.pi/4)*(1+float(i)/N)
+ SectionResult = CutnGroup.Go(WMBezier, [(0,0,0,math.sin(TempAnglePlus),-math.cos(TempAnglePlus),0)], [1], ['Dummy'], 0)
+ TempPt1 = SectionResult[1][0]
+ TempPt11 = geompy.MakeVertex ((N-i)*X/N, 10., 0)
+
+ TempAngleMinus = (math.pi/4)*(1-float(i)/N)
+ SectionResult = CutnGroup.Go(SMBezier, [(0,0,0,math.sin(TempAngleMinus),-math.cos(TempAngleMinus),0)], [1], ['Dummy'], 0)
+ TempPt2 = SectionResult[1][0]
+ TempPt21 = geompy.MakeVertex (10., (N-i)*X/N, 0)
+
+ Cutter.append(geompy.MakeEdge(SouthWestPt, TempPt1))
+ Cutter.append(geompy.MakeEdge(SouthWestPt, TempPt2))
+ Cutter.append(geompy.MakeEdge(TempPt1, TempPt11))
+ Cutter.append(geompy.MakeEdge(TempPt2, TempPt21))
+
+ CylFace = geompy.MakePartition([CylFace],Cutter, [], [],4, 0, [], 0) #Creating the partition object
+ CylFace = geompy.MakeTranslation(CylFace, -5., -5., 0.0)
+
+ return CylFace
+
def CompatibilityTest(MacObject):
- Type = MacObject.Type
- if Type == 'Box11' :
- BaseDirPar = [1,1,1,1]
- return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
- elif Type == 'Box42' :
- BaseDirPar = {'SN' : lambda : [3, 3, 4, 2],
- 'NS' : lambda : [3, 3, 2, 4],
- 'EW' : lambda : [2, 4, 3, 3],
- 'WE' : lambda : [4, 2, 3, 3], }[MacObject.MeshPar[1]]()
- return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
- elif Type == 'BoxAng32' :
- BaseDirPar = {'NE' : lambda : [3, 2, 3, 2],
- 'NW' : lambda : [2, 3, 3, 2],
- 'SW' : lambda : [2, 3, 2, 3],
- 'SE' : lambda : [3, 2, 2, 3], }[MacObject.MeshPar[1]]()
- return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
- elif Type == 'CompBox' :
- #print "dx is: ", MacObject.GeoPar[1][1], ". dy is: ",MacObject.GeoPar[1][0]
- ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0], MacObject.GeoPar[1][1])
- #print ReducedRatio
- BaseDirPar = [ReducedRatio[1], ReducedRatio[1], ReducedRatio[0], ReducedRatio[0]]
- return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
-
- elif Type == 'QuartCyl' :
- N = QuarCylParam(MacObject.MeshPar[2])+1
- BaseDirPar = {'NE' : lambda : [2, N, 2, N],
- 'NW' : lambda : [N, 2, 2, N],
- 'SW' : lambda : [N, 2, N, 2],
- 'SE' : lambda : [2, N, N, 2], }[MacObject.MeshPar[1]]()
- return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
- elif Type == 'CompBoxF' :
- RealRatio = MacObject.GeoPar[1][1]/MacObject.GeoPar[1][0]
- Xd = 0
- Yd = 0
- if MacObject.DirectionalMeshParams[2]+MacObject.DirectionalMeshParams[3] :
- A = int(max(MacObject.DirectionalMeshParams[2:4]))
- Xd = int(VecDivRatio([A,0,0,0], [1,1,1,1]))
- if MacObject.DirectionalMeshParams[0]+MacObject.DirectionalMeshParams[1] :
- A = int(max(MacObject.DirectionalMeshParams[0:2]))
- Yd = int(VecDivRatio([0,0,A,0], [1,1,1,1]))
-
- if Xd == 0 and Yd : Xd = int(round(Yd/RealRatio))
- elif Yd == 0 : Yd = int(round(RealRatio*Xd))
-
- return [Xd,Yd]
- elif Type == 'NonOrtho' :
- MeanDX = 0.5*(IntLen(MacObject.DirBoundaries(0))+IntLen(MacObject.DirBoundaries(1)))
- MeanDY = 0.5*(IntLen(MacObject.DirBoundaries(2))+IntLen(MacObject.DirBoundaries(3)))
- RealRatio = MeanDY/MeanDX
- Xd = 0
- Yd = 0
- if MacObject.DirectionalMeshParams[2]+MacObject.DirectionalMeshParams[3] :
- A = int(max(MacObject.DirectionalMeshParams[2:4]))
- Xd = int(VecDivRatio([A,0,0,0], [1,1,1,1]))
- if MacObject.DirectionalMeshParams[0]+MacObject.DirectionalMeshParams[1] :
- A = int(max(MacObject.DirectionalMeshParams[0:2]))
- Yd = int(VecDivRatio([0,0,A,0], [1,1,1,1]))
-
- if Xd == 0 and Yd : Xd = int(round(Yd/RealRatio))
- elif Yd == 0 : Yd = int(round(RealRatio*Xd))
-
- return [Xd,Yd]
+ Type = MacObject.Type
+ if Type == 'Box11' :
+ BaseDirPar = [1,1,1,1]
+ return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
+ elif Type == 'Box42' :
+ BaseDirPar = {'SN' : lambda : [3, 3, 4, 2],
+ 'NS' : lambda : [3, 3, 2, 4],
+ 'EW' : lambda : [2, 4, 3, 3],
+ 'WE' : lambda : [4, 2, 3, 3], }[MacObject.MeshPar[1]]()
+ return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
+ elif Type == 'BoxAng32' :
+ BaseDirPar = {'NE' : lambda : [3, 2, 3, 2],
+ 'NW' : lambda : [2, 3, 3, 2],
+ 'SW' : lambda : [2, 3, 2, 3],
+ 'SE' : lambda : [3, 2, 2, 3], }[MacObject.MeshPar[1]]()
+ return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
+ elif Type == 'CompBox' :
+ #print "dx is: ", MacObject.GeoPar[1][1], ". dy is: ",MacObject.GeoPar[1][0]
+ ReducedRatio = ReduceRatio(MacObject.GeoPar[1][0], MacObject.GeoPar[1][1])
+ #print ReducedRatio
+ BaseDirPar = [ReducedRatio[1], ReducedRatio[1], ReducedRatio[0], ReducedRatio[0]]
+ return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
+
+ elif Type == 'QuartCyl' :
+ N = QuarCylParam(MacObject.MeshPar[2])+1
+ BaseDirPar = {'NE' : lambda : [2, N, 2, N],
+ 'NW' : lambda : [N, 2, 2, N],
+ 'SW' : lambda : [N, 2, N, 2],
+ 'SE' : lambda : [2, N, N, 2], }[MacObject.MeshPar[1]]()
+ return int(VecDivRatio(MacObject.DirectionalMeshParams, BaseDirPar))
+ elif Type == 'CompBoxF' :
+ RealRatio = MacObject.GeoPar[1][1]/MacObject.GeoPar[1][0]
+ Xd = 0
+ Yd = 0
+ if MacObject.DirectionalMeshParams[2]+MacObject.DirectionalMeshParams[3] :
+ A = int(max(MacObject.DirectionalMeshParams[2:4]))
+ Xd = int(VecDivRatio([A,0,0,0], [1,1,1,1]))
+ if MacObject.DirectionalMeshParams[0]+MacObject.DirectionalMeshParams[1] :
+ A = int(max(MacObject.DirectionalMeshParams[0:2]))
+ Yd = int(VecDivRatio([0,0,A,0], [1,1,1,1]))
+
+ if Xd == 0 and Yd : Xd = int(round(Yd/RealRatio))
+ elif Yd == 0 : Yd = int(round(RealRatio*Xd))
+
+ return [Xd,Yd]
+ elif Type == 'NonOrtho' :
+ MeanDX = 0.5*(IntLen(MacObject.DirBoundaries(0))+IntLen(MacObject.DirBoundaries(1)))
+ MeanDY = 0.5*(IntLen(MacObject.DirBoundaries(2))+IntLen(MacObject.DirBoundaries(3)))
+ RealRatio = MeanDY/MeanDX
+ Xd = 0
+ Yd = 0
+ if MacObject.DirectionalMeshParams[2]+MacObject.DirectionalMeshParams[3] :
+ A = int(max(MacObject.DirectionalMeshParams[2:4]))
+ Xd = int(VecDivRatio([A,0,0,0], [1,1,1,1]))
+ if MacObject.DirectionalMeshParams[0]+MacObject.DirectionalMeshParams[1] :
+ A = int(max(MacObject.DirectionalMeshParams[0:2]))
+ Yd = int(VecDivRatio([0,0,A,0], [1,1,1,1]))
+
+ if Xd == 0 and Yd : Xd = int(round(Yd/RealRatio))
+ elif Yd == 0 : Yd = int(round(RealRatio*Xd))
+
+ return [Xd,Yd]
def IntLen (Interval) :
- """
- This function returns the length of a given interval even if the latter is not sorted correctly.
- """
- return abs(Interval[1]-Interval[0])
-
+ """
+ This function returns the length of a given interval even if the latter is not sorted correctly.
+ """
+ return abs(Interval[1]-Interval[0])
+
def NextTo (RefBox, Direction, Extension):
- """
- This functions returns geometrical parameters for easy positioning of neighbouring objects.
- The input (RefBox) and output are in the form : [(X0,Y0),(DX,DY)]
- """
- X0_0 = RefBox[0][0]
- Y0_0 = RefBox[0][1]
- DX_0 = RefBox[1][0]
- DY_0 = RefBox[1][1]
-
- DirectionalCoef = {'Above' : lambda : [ 0, 1],
- 'Below' : lambda : [ 0,-1],
- 'Right' : lambda : [ 1, 0],
- 'Left ' : lambda : [-1, 0], }[Direction]()
-
- X0_1 = X0_0+ DirectionalCoef[0] * (DX_0/2.+Extension/2.)
- DX_1 = abs(DirectionalCoef[0]) * (Extension) + abs(DirectionalCoef[1])*DX_0
- Y0_1 = Y0_0+ DirectionalCoef[1] * (DY_0/2.+Extension/2.)
- DY_1 = abs(DirectionalCoef[1]) * (Extension) + abs(DirectionalCoef[0])*DY_0
-
- return [(X0_1,Y0_1),(DX_1,DY_1)]
-
+ """
+ This functions returns geometrical parameters for easy positioning of neighbouring objects.
+ The input (RefBox) and output are in the form : [(X0,Y0),(DX,DY)]
+ """
+ X0_0 = RefBox[0][0]
+ Y0_0 = RefBox[0][1]
+ DX_0 = RefBox[1][0]
+ DY_0 = RefBox[1][1]
+
+ DirectionalCoef = {'Above' : lambda : [ 0, 1],
+ 'Below' : lambda : [ 0,-1],
+ 'Right' : lambda : [ 1, 0],
+ 'Left ' : lambda : [-1, 0], }[Direction]()
+
+ X0_1 = X0_0+ DirectionalCoef[0] * (DX_0/2.+Extension/2.)
+ DX_1 = abs(DirectionalCoef[0]) * (Extension) + abs(DirectionalCoef[1])*DX_0
+ Y0_1 = Y0_0+ DirectionalCoef[1] * (DY_0/2.+Extension/2.)
+ DY_1 = abs(DirectionalCoef[1]) * (Extension) + abs(DirectionalCoef[0])*DY_0
+
+ return [(X0_1,Y0_1),(DX_1,DY_1)]
+
def GeomMinMax (PtA, PtB):
- """
- This function returns geometrical parameters in the format [(X0,Y0),(DX,DY)]. The input being
- the coordinates of two points (Xa,Ya), (Xb,Yb).
- """
- # First test that the vector relying the two points is oblique
- AB = [PtB[0]- PtA[0],PtB[1]- PtA[1]]
- if 0 in AB :
- print ("Error: the two points are not correctly defined. In the orthonormal system XOY, it is impossible to define a rectangle with these two points")
- return -1
- else:
- X0 = 0.5*(PtA[0]+PtB[0])
- Y0 = 0.5*(PtA[1]+PtB[1])
- DX = abs(AB[0])
- DY = abs(AB[1])
- return [(X0,Y0),(DX,DY)]
+ """
+ This function returns geometrical parameters in the format [(X0,Y0),(DX,DY)]. The input being
+ the coordinates of two points (Xa,Ya), (Xb,Yb).
+ """
+ # First test that the vector relying the two points is oblique
+ AB = [PtB[0]- PtA[0],PtB[1]- PtA[1]]
+ if 0 in AB :
+ print ("Error: the two points are not correctly defined. In the orthonormal system XOY, it is impossible to define a rectangle with these two points")
+ return -1
+ else:
+ X0 = 0.5*(PtA[0]+PtB[0])
+ Y0 = 0.5*(PtA[1]+PtB[1])
+ DX = abs(AB[0])
+ DY = abs(AB[1])
+ return [(X0,Y0),(DX,DY)]
def AddIfDifferent (List, Element):
- if not(Element in List):
- List = List+(Element,)
- return List
+ if not(Element in List):
+ List = List+(Element,)
+ return List
def IndexMultiOcc (Array,Element) :
- """
- This functions returns the occurrences indices of Element in Array.
- As opposed to Array.index(Element) method, this allows determining
- multiple entries rather than just the first one!
- """
- Output = []
- try : Array.index(Element)
- except ValueError : print "No more occurrences"
- else : Output.append(Array.index(Element))
-
- if not(Output == []) and len(Array) > 1 :
- for index, ArrElem in enumerate(Array[Output[0]+1:]) :
- if ArrElem == Element : Output.append(index+Output[0]+1)
-
- return Output
-
+ """
+ This functions returns the occurrences indices of Element in Array.
+ As opposed to Array.index(Element) method, this allows determining
+ multiple entries rather than just the first one!
+ """
+ Output = []
+ try : Array.index(Element)
+ except ValueError : print("No more occurrences")
+ else : Output.append(Array.index(Element))
+
+ if not(Output == []) and len(Array) > 1 :
+ for index, ArrElem in enumerate(Array[Output[0]+1:]) :
+ if ArrElem == Element : Output.append(index+Output[0]+1)
+
+ return Output
+
def SortList (ValList, CritList):
- Output = []
- SortedCritList = copy.copy(CritList)
- SortedCritList.sort()
- for i in range(0,len(ValList)):
- if i > 0 :
- if not(SortedCritList[i]==SortedCritList[i-1]):
- index = IndexMultiOcc(CritList,SortedCritList[i])
- Output= Output + [ValList[j] for j in index]
- else :
- index = IndexMultiOcc(CritList,SortedCritList[i])
- Output= Output + [ValList[j] for j in index]
-
- return Output
+ Output = []
+ SortedCritList = sorted(copy.copy(CritList))
+ for i in range(0,len(ValList)):
+ if i > 0 :
+ if not(SortedCritList[i]==SortedCritList[i-1]):
+ index = IndexMultiOcc(CritList,SortedCritList[i])
+ Output= Output + [ValList[j] for j in index]
+ else :
+ index = IndexMultiOcc(CritList,SortedCritList[i])
+ Output= Output + [ValList[j] for j in index]
+
+ return Output
def SortPoints(Points):
- """
- This function sorts a list of the coordinates of N points as to start at
- an origin that represents Xmin and Xmax and then proceed in a counter
- clock-wise sense
- """
- NbPts = len(Points)
- Xmin = min([Points[i][0] for i in range(NbPts)])
- Ymin = min([Points[i][1] for i in range(NbPts)])
- Xmax = max([Points[i][0] for i in range(NbPts)])
- Ymax = max([Points[i][1] for i in range(NbPts)])
- Crit = [(abs(Point[0]-Xmin)+0.1*(Xmax-Xmin))*(abs(Point[1]-Ymin)+0.1*(Ymax-Ymin)) for Point in Points]
- #print "Input Points : ", Points
- #print "Sorting Criterion : ", Crit
- Order = SortList (range(NbPts), Crit)
- #print "Sorted Results : ", Order
- Output = []
- Output.append(Points[Order[0]])
-
- Point0 = Points[Order[0]]
- #print "Reference point :", Point0
-
- V = [[Point1[0]-Point0[0],Point1[1]-Point0[1]] for Point1 in Points]
- Cosines = [-(vec[0]-1E-10)/(math.sqrt(DotProd(vec,vec)+1e-25)) for vec in V]
- #print "Cosines criterion :", Cosines
- Order = SortList(range(NbPts),Cosines)
- #print "Ordered points:", Order
- for PtIndex in Order[:-1]: Output.append(Points[PtIndex])
-
- return Output
-
+ """
+ This function sorts a list of the coordinates of N points as to start at
+ an origin that represents Xmin and Xmax and then proceed in a counter
+ clock-wise sense
+ """
+ NbPts = len(Points)
+ Xmin = min([Points[i][0] for i in range(NbPts)])
+ Ymin = min([Points[i][1] for i in range(NbPts)])
+ Xmax = max([Points[i][0] for i in range(NbPts)])
+ Ymax = max([Points[i][1] for i in range(NbPts)])
+ Crit = [(abs(Point[0]-Xmin)+0.1*(Xmax-Xmin))*(abs(Point[1]-Ymin)+0.1*(Ymax-Ymin)) for Point in Points]
+ #print "Input Points : ", Points
+ #print "Sorting Criterion : ", Crit
+ Order = SortList (list(range(NbPts)), Crit)
+ #print "Sorted Results : ", Order
+ Output = []
+ Output.append(Points[Order[0]])
+
+ Point0 = Points[Order[0]]
+ #print "Reference point :", Point0
+
+ V = [[Point1[0]-Point0[0],Point1[1]-Point0[1]] for Point1 in Points]
+ Cosines = [-(vec[0]-1E-10)/(math.sqrt(DotProd(vec,vec)+1e-25)) for vec in V]
+ #print "Cosines criterion :", Cosines
+ Order = SortList(list(range(NbPts)),Cosines)
+ #print "Ordered points:", Order
+ for PtIndex in Order[:-1]: Output.append(Points[PtIndex])
+
+ return Output
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
- #
+ #
import SMESH
import math
import Config
from salome.geom import geomBuilder
-geompy = geomBuilder.New( Config.theStudy )
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New( Config.theStudy )
+smesh = smeshBuilder.New()
##########################################################################################################
def PublishGroups ():
- aFilterManager = smesh.CreateFilterManager()
+ aFilterManager = smesh.CreateFilterManager()
+
+ # Building geometric and mesh compounds and groups ##############################################
+ if Config.debug : print("Searching for geometric groups and publishing final compound")
+
+ TempGEOList = []
+ TempMESHList = []
+
+ for MacroObj in Config.ListObj :
+ TempGEOList += MacroObj.GeoChildren
+ TempMESHList += MacroObj.Mesh
- # Building geometric and mesh compounds and groups ##############################################
- if Config.debug : print "Searching for geometric groups and publishing final compound"
-
+ FinalCompound = geompy.MakeCompound(TempGEOList)
+ geompy.addToStudy (FinalCompound,Config.StudyName)
+ MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
+ MeshCompound.SetName(Config.StudyName)
+
+ GroupGEO = []
+ for group in Config.Groups :
+
+ # Geometric groups definition
TempGEOList = []
- TempMESHList = []
-
- for MacroObj in Config.ListObj :
- TempGEOList += MacroObj.GeoChildren
- TempMESHList += MacroObj.Mesh
-
- FinalCompound = geompy.MakeCompound(TempGEOList)
- geompy.addToStudy (FinalCompound,Config.StudyName)
- MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
- MeshCompound.SetName(Config.StudyName)
-
- GroupGEO = []
- for group in Config.Groups :
-
- # Geometric groups definition
- TempGEOList = []
- TempNames = []
- for MacroObj in Config.ListObj :
- if group in MacroObj.GroupNames :
- Occurences = IndexMultiOcc(MacroObj.GroupNames, group)
- for Occ in Occurences :
- TempGEOList += MacroObj.GetBorder(Occ)
- GroupGEO.append(geompy.MakeCompound(TempGEOList))
- geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
-
- # Mesh groups definition
- Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
- #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
- MeshCompound.MakeGroupByCriterion(group,Criterion)
-
- StudyBuilder = Config.theStudy.NewBuilder()
- for MeshObj in TempMESHList:
- SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
- if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
-
- return MeshCompound
-
+ TempNames = []
+ for MacroObj in Config.ListObj :
+ if group in MacroObj.GroupNames :
+ Occurences = IndexMultiOcc(MacroObj.GroupNames, group)
+ for Occ in Occurences :
+ TempGEOList += MacroObj.GetBorder(Occ)
+ GroupGEO.append(geompy.MakeCompound(TempGEOList))
+ geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
+
+ # Mesh groups definition
+ Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
+ #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
+ MeshCompound.MakeGroupByCriterion(group,Criterion)
+
+ StudyBuilder = Config.theStudy.NewBuilder()
+ for MeshObj in TempMESHList:
+ SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
+ if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
+
+ return MeshCompound
+
def IndexMultiOcc (Array,Element) :
- """
- This function returns the occurrences indices of Element in Array.
- As opposed to Array.index(Element) method, this allows determining
- multiple entries rather than just the first one!
- """
- Output = []
- try : Array.index(Element)
- except ValueError : print "No more occurrences"
- else : Output.append(Array.index(Element))
-
- if not(Output == [-1]) and len(Array) > 1 :
- for index, ArrElem in enumerate(Array[Output[0]+1:]) :
- if ArrElem is Element : Output.append(index+Output[0]+1)
-
- return Output
-
+ """
+ This function returns the occurrences indices of Element in Array.
+ As opposed to Array.index(Element) method, this allows determining
+ multiple entries rather than just the first one!
+ """
+ Output = []
+ try : Array.index(Element)
+ except ValueError : print("No more occurrences")
+ else : Output.append(Array.index(Element))
+
+ if not(Output == [-1]) and len(Array) > 1 :
+ for index, ArrElem in enumerate(Array[Output[0]+1:]) :
+ if ArrElem is Element : Output.append(index+Output[0]+1)
+
+ return Output
+
def Publish (ObjToPublish):
- for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i))
-
+ for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i))
+
def RevolveMesh(MainMesh,**args):
- """
- This function premits to revolute and scale a 2D mesh while transforming the edge
- groups into face groups. Moreover, the function automatically creates the face groups
- corresponding to the symmetry lower and upper faces
- Facultatif arguments are :
- - Center [X,Y,Z], origin being the default
- - Direction [VX,VY,VZ], x-axis being the default
- - AngleDeg or AngleRad : ALPHA, 10 degrees being the default
- - Scale : BETA, no scaling being default
- """
- ################################################################################
- # Reading input arguments and proceeding to defaults if necessary
- ################################################################################
- if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']]
- else :
- print "\nThe coordinates of the center of revolution were not given\nThe origin is used by default."
- CenterCoor = [0.,0.,0.]
-
- if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']]
- else :
- print "\nThe axis vector of revolution was not given\nThe x-axis is used by default."
- Direction = [1.,0.,0.]
-
- if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180.
- elif 'AngleRad' in args : Angle = float(args['AngleRad'])
- else :
- print "\nThe revolution angle was not given\nAn angle of 10 degrees is used by default."
- Angle = 10.*math.pi/180.
-
- if 'Scale' in args : Scale = float(args['Scale'])
- else : Scale = 1.
-
-
- # Creating the lower face group LOFAC
- LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
- LOFAC.AddFrom(MainMesh.GetMesh())
-
- GR_Names = MainMesh.GetGroupNames()
- GRs = MainMesh.GetGroups()
- Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True)
-
- # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
- for GR in GRs:
- CurrentName = GR.GetName()
- if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
- GR.SetName(CurrentName+'_EDGE')
-
- # Removing the _rotated prefix from the rotated FACE groups
- for GR in Rev3DMeshGroups:
- CurrentName = GR.GetName()
- if CurrentName.endswith( "_rotated"):
- if CurrentName.startswith( 'LOFAC_' ):
- GR.SetName('VOL')
- else:
- GR.SetName(CurrentName[:-8])
- elif CurrentName == 'LOFAC_top':
- GR.SetName('HIFAC')
- #Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True)
- #GR.SetName(GR_Names[Index])
-
- # Creating the upper face group HIFAC
- ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
- ALLFAC.AddFrom(MainMesh.GetMesh())
-
- #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
- #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' )
-
- # Scaling down the mesh to meter units
- if not(Scale==1.):
- MeshEditor = MainMesh.GetMeshEditor()
- MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
-
-
+ """
+ This function premits to revolute and scale a 2D mesh while transforming the edge
+ groups into face groups. Moreover, the function automatically creates the face groups
+ corresponding to the symmetry lower and upper faces
+ Facultatif arguments are :
+ - Center [X,Y,Z], origin being the default
+ - Direction [VX,VY,VZ], x-axis being the default
+ - AngleDeg or AngleRad : ALPHA, 10 degrees being the default
+ - Scale : BETA, no scaling being default
+ """
+ ################################################################################
+ # Reading input arguments and proceeding to defaults if necessary
+ ################################################################################
+ if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']]
+ else :
+ print("\nThe coordinates of the center of revolution were not given\nThe origin is used by default.")
+ CenterCoor = [0.,0.,0.]
+
+ if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']]
+ else :
+ print("\nThe axis vector of revolution was not given\nThe x-axis is used by default.")
+ Direction = [1.,0.,0.]
+
+ if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180.
+ elif 'AngleRad' in args : Angle = float(args['AngleRad'])
+ else :
+ print("\nThe revolution angle was not given\nAn angle of 10 degrees is used by default.")
+ Angle = 10.*math.pi/180.
+
+ if 'Scale' in args : Scale = float(args['Scale'])
+ else : Scale = 1.
+
+
+ # Creating the lower face group LOFAC
+ LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
+ LOFAC.AddFrom(MainMesh.GetMesh())
+
+ GR_Names = MainMesh.GetGroupNames()
+ GRs = MainMesh.GetGroups()
+ Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True)
+
+ # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
+ for GR in GRs:
+ CurrentName = GR.GetName()
+ if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
+ GR.SetName(CurrentName+'_EDGE')
+
+ # Removing the _rotated prefix from the rotated FACE groups
+ for GR in Rev3DMeshGroups:
+ CurrentName = GR.GetName()
+ if CurrentName.endswith( "_rotated"):
+ if CurrentName.startswith( 'LOFAC_' ):
+ GR.SetName('VOL')
+ else:
+ GR.SetName(CurrentName[:-8])
+ elif CurrentName == 'LOFAC_top':
+ GR.SetName('HIFAC')
+ #Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True)
+ #GR.SetName(GR_Names[Index])
+
+ # Creating the upper face group HIFAC
+ ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
+ ALLFAC.AddFrom(MainMesh.GetMesh())
+
+ #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
+ #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' )
+
+ # Scaling down the mesh to meter units
+ if not(Scale==1.):
+ MeshEditor = MainMesh.GetMeshEditor()
+ MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
+
+
def ExtrudeMesh(MainMesh,**args):
- """
- This function premits to extrude and scale a 2D mesh while transforming the edge
- groups into face groups. Moreover, the function automatically creates the face groups
- corresponding to the symmetry lower and upper faces
- Facultatif arguments are :
- - Direction [VX,VY,VZ], z-axis being default
- - Distance : D, default is 1
- - NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1
- - Scale : BETA, no scaling being default
- """
- ################################################################################
- # Reading input arguments and proceeding to defaults if necessary
- ################################################################################
- if 'Distance' in args : Distance = float(args['Distance'])
- else :
- print "\nThe extrusion distance was not given\nA default value of 1 is used."
- Distance = 1.
-
- if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance)
- else :
- print "\nThe extrusion vector of revolution was not given\nThe z-axis is used by default."
- Direction = NormalizeVector([0.,0.,1.],Distance)
-
- if 'Scale' in args : Scale = float(args['Scale'])
- else : Scale = 1.
-
- if 'NSteps' in args : NSteps = int(args['NSteps'])
- else : NSteps = 1
-
- # Creating the lower face group LOFAC
- LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
- LOFAC.AddFrom(MainMesh.GetMesh())
-
- GR_Names = MainMesh.GetGroupNames()
- GRs = MainMesh.GetGroups()
- Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True)
-
- # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
- for GR in GRs:
- CurrentName = GR.GetName()
- if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
- GR.SetName(CurrentName+'_EDGE')
-
- # Removing the _extruded suffix from the extruded FACE groups
- for GR in Ext3DMeshGroups:
- CurrentName = GR.GetName()
- if CurrentName.endswith( "_extruded"):
- if CurrentName.startswith( 'LOFAC_' ):
- GR.SetName('VOL')
- else:
- GR.SetName(CurrentName[:-9])
- elif CurrentName == 'LOFAC_top':
- GR.SetName('HIFAC')
-
- # Creating the upper face group HIFAC
- ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
- ALLFAC.AddFrom(MainMesh.GetMesh())
-
- #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
-
- # Scaling down the mesh to meter units
- if not(Scale==1.):
- MeshEditor = MainMesh.GetMeshEditor()
- MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
-
-
+ """
+ This function premits to extrude and scale a 2D mesh while transforming the edge
+ groups into face groups. Moreover, the function automatically creates the face groups
+ corresponding to the symmetry lower and upper faces
+ Facultatif arguments are :
+ - Direction [VX,VY,VZ], z-axis being default
+ - Distance : D, default is 1
+ - NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1
+ - Scale : BETA, no scaling being default
+ """
+ ################################################################################
+ # Reading input arguments and proceeding to defaults if necessary
+ ################################################################################
+ if 'Distance' in args : Distance = float(args['Distance'])
+ else :
+ print("\nThe extrusion distance was not given\nA default value of 1 is used.")
+ Distance = 1.
+
+ if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance)
+ else :
+ print("\nThe extrusion vector of revolution was not given\nThe z-axis is used by default.")
+ Direction = NormalizeVector([0.,0.,1.],Distance)
+
+ if 'Scale' in args : Scale = float(args['Scale'])
+ else : Scale = 1.
+
+ if 'NSteps' in args : NSteps = int(args['NSteps'])
+ else : NSteps = 1
+
+ # Creating the lower face group LOFAC
+ LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
+ LOFAC.AddFrom(MainMesh.GetMesh())
+
+ GR_Names = MainMesh.GetGroupNames()
+ GRs = MainMesh.GetGroups()
+ Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True)
+
+ # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
+ for GR in GRs:
+ CurrentName = GR.GetName()
+ if CurrentName in GR_Names and not(CurrentName=='LOFAC'): # Meaning that this is an old edge group
+ GR.SetName(CurrentName+'_EDGE')
+
+ # Removing the _extruded suffix from the extruded FACE groups
+ for GR in Ext3DMeshGroups:
+ CurrentName = GR.GetName()
+ if CurrentName.endswith( "_extruded"):
+ if CurrentName.startswith( 'LOFAC_' ):
+ GR.SetName('VOL')
+ else:
+ GR.SetName(CurrentName[:-9])
+ elif CurrentName == 'LOFAC_top':
+ GR.SetName('HIFAC')
+
+ # Creating the upper face group HIFAC
+ ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
+ ALLFAC.AddFrom(MainMesh.GetMesh())
+
+ #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
+
+ # Scaling down the mesh to meter units
+ if not(Scale==1.):
+ MeshEditor = MainMesh.GetMeshEditor()
+ MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
+
+
def NormalizeVector (V,Norm):
- """
- This function returns a normalized vector (magnitude = Norm), parallel to the entered one
- """
- V = [float(Coor) for Coor in V]
- Norm = float(Norm)
- MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2])
- return [Coor*Norm/MagV for Coor in V]
-
+ """
+ This function returns a normalized vector (magnitude = Norm), parallel to the entered one
+ """
+ V = [float(Coor) for Coor in V]
+ Norm = float(Norm)
+ MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2])
+ return [Coor*Norm/MagV for Coor in V]
# if not, copy this file as ${HOME}/Plugins/smesh_plugins.py or ${APPLI}/Plugins/smesh_plugins.py
def MeshCut(context):
- # get context study, studyId, salomeGui
+ # get context study, salomeGui
study = context.study
- studyId = context.studyId
sg = context.sg
import os
if fd.exec_():
infile = fd.selectedFiles()[0]
self.ui.le_origMeshFile.setText(infile)
- insplit = os.path.splitext(unicode(infile).encode())
+ insplit = os.path.splitext(str(infile).encode())
outfile = insplit[0] + '_cut' + insplit[1]
self.ui.le_cutMeshFile.setText(outfile)
pass
if result:
# dialog accepted
args = ['MeshCut']
- args += [unicode(window.ui.le_origMeshFile.text()).encode()]
- args += [unicode(window.ui.le_cutMeshFile.text()).encode()]
- args += [unicode(window.ui.le_outMeshName.text()).encode()]
- args += [unicode(window.ui.le_groupAbove.text()).encode()]
- args += [unicode(window.ui.le_groupBelow.text()).encode()]
+ args += [str(window.ui.le_origMeshFile.text()).encode()]
+ args += [str(window.ui.le_cutMeshFile.text()).encode()]
+ args += [str(window.ui.le_outMeshName.text()).encode()]
+ args += [str(window.ui.le_groupAbove.text()).encode()]
+ args += [str(window.ui.le_groupBelow.text()).encode()]
args += [str(window.ui.dsb_normX.value())]
args += [str(window.ui.dsb_normY.value())]
args += [str(window.ui.dsb_normZ.value())]
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
+ #!/usr/bin/env python3
import sys,os
import salome
- from getStats import getGroupesRef
- from Type_Maille import dicoDimENtite
+ from .getStats import getGroupesRef
+ from .Type_Maille import dicoDimENtite
-def getCritere(dim,NomMesh,acritere,theStudy):
+def getCritere(dim,NomMesh,acritere):
import SMESH
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(theStudy)
+ smesh = smeshBuilder.New()
import numpy
# print dim,NomMesh,acritere
if dim == 2 :
return [max,min,Q1,M,Q3,moyenne]
-def getCritereGroupe(NomMesh,NomGr,acritere,theStudy):
+def getCritereGroupe(NomMesh,NomGr,acritere):
import SMESH
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(theStudy)
+ smesh = smeshBuilder.New()
import numpy
# on ne traite que les mailles 2D et 3D
return [max,min,Q1,M,Q3,moyenne]
-def getObjectsGroupe(Mesh,liste,theStudy):
+def getObjectsGroupe(Mesh,liste):
import SMESH
from salome.smesh import smeshBuilder
dico={}
if name == n : dico[name]=g
return dico
-def getStatsCritere(dim,Mesh,fichierMedResult,theStudy):
+def getStatsCritere(dim,Mesh,fichierMedResult):
fichierStatRatio=fichierMedResult.replace('.med','.ratio')
- max,min,Q1,M,Q3,moyenne = getCritere(dim,Mesh,"Ratio",theStudy)
+ max,min,Q1,M,Q3,moyenne = getCritere(dim,Mesh,"Ratio")
f = open(fichierStatRatio, 'w')
f.write(str(max)+","+str(min)+","+str(Q1)+","+str(M)+","+str(Q3)+","+str(moyenne))
f.close()
fichierStatRatio=fichierMedResult.replace('.med','.taille')
- max,min,Q1,M,Q3,moyenne = getCritere(dim,Mesh,"Length",theStudy)
+ max,min,Q1,M,Q3,moyenne = getCritere(dim,Mesh,"Length")
f = open(fichierStatRatio, 'w')
f.write(str(max)+","+str(min)+","+str(Q1)+","+str(M)+","+str(Q3)+","+str(moyenne))
f.close()
liste=getGroupesRef(fichierMedResult)
- dicoGroupe=getObjectsGroupe(Mesh,liste,theStudy)
+ dicoGroupe=getObjectsGroupe(Mesh,liste)
for groupe in liste :
- max,min,Q1,M,Q3,moyenne=getCritereGroupe(Mesh,dicoGroupe[groupe],"Ratio",theStudy)
+ max,min,Q1,M,Q3,moyenne=getCritereGroupe(Mesh,dicoGroupe[groupe],"Ratio")
extension="_"+groupe+'_Ratio.res'
fichier=fichierMedResult.replace('.med',extension)
f = open(fichier, 'w')
f.write(str(max)+","+str(min)+","+str(Q1)+","+str(M)+","+str(Q3)+","+str(moyenne))
f.close()
- max,min,Q1,M,Q3,moyenne=getCritereGroupe(Mesh,dicoGroupe[groupe],"Length",theStudy)
+ max,min,Q1,M,Q3,moyenne=getCritereGroupe(Mesh,dicoGroupe[groupe],"Length")
extension="_"+groupe+'_Taille.res'
fichier=fichierMedResult.replace('.med',extension)
f = open(fichier, 'w')
import SMESH
from salome.kernel import studyedit
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
if not os.path.isfile(self.fichierOut):
QMessageBox.warning(self, "Compute", "Result file "+self.fichierOut+" not found")
- maStudy=studyedit.getActiveStudy()
- smesh.SetCurrentStudy(maStudy)
+ maStudy=salome.myStudy
+ smesh.UpdateStudy()
(outputMesh, status) = smesh.CreateMeshesFromGMF(self.fichierOut)
name=str(self.LE_MeshSmesh.text())
initialMeshFile=None
newLink=monStudyBuilder.NewObject(SOMesh)
monStudyBuilder.Addreference(newLink, newStudyIter)
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num+=1
return True
#myStudy.IsStudyLocked()
myComponent = myStudy.FindComponent(name)
if myComponent == None:
- print "myComponent not found, create"
+ print("myComponent not found, create")
myComponent = myBuilder.NewComponent(name)
AName = myBuilder.FindOrCreateAttribute(myComponent, "AttributeName")
AName.SetValue(name)
ACmt = myBuilder.FindOrCreateAttribute(myObject, "AttributeComment")
ACmt.SetValue(datai)
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num += 1
- if verbose: print("save %s in Object Browser done: %s\n%s" % (name, myObject.GetID(), datai))
+ if verbose: print(("save %s in Object Browser done: %s\n%s" % (name, myObject.GetID(), datai)))
return True
def PBSaveHypPressed(self):
QMessageBox.warning(self, "Save", "waiting for fix: Object Browser will not display hypothesis")
if verbose: print("save hypothesis in Object Browser")
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
- maStudy=studyedit.getActiveStudy()
- smesh.SetCurrentStudy(maStudy)
+ maStudy=salome.myStudy
+ smesh.UpdateStudy()
self.editor = studyedit.getStudyEditor()
moduleEntry=self.editor.findOrCreateComponent("SMESH","SMESH")
data = self.getResumeData(separator=" ; ")
self.editor.setAttributeValue(newStudyIter, "AttributeComment", data)
- if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
+ if salome.sg.hasDesktop(): salome.sg.updateObjBrowser()
self.num += 1
- if verbose: print("save %s in Object Browser done:\n%s" % (name, data))
+ if verbose: print(("save %s in Object Browser done:\n%s" % (name, data)))
return True
def SP_toStr(self, widget):
if fd.exec_():
infile = fd.selectedFiles()[0]
self.LE_MeshFile.setText(infile)
- self.fichierIn=unicode(infile).encode("latin-1")
+ self.fichierIn=str(infile).encode("latin-1")
self.MeshIn=""
self.LE_MeshSmesh.setText("")
if fd.exec_():
infile = fd.selectedFiles()[0]
self.LE_ParamsFile.setText(infile)
- self.paramsFile=unicode(infile).encode("latin-1")
+ self.paramsFile=str(infile).encode("latin-1")
def meshFileNameChanged(self):
self.fichierIn=str(self.LE_MeshFile.text())
from salome.smesh.smeshstudytools import SMeshStudyTools
from salome.gui import helper as guihelper
from salome.smesh import smeshBuilder
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
mySObject, myEntry = guihelper.getSObjectSelected()
if CORBA.is_nil(mySObject) or mySObject==None:
except:
pass
- style = unicode(self.style).encode("latin-1")
+ style = str(self.style).encode("latin-1")
# Translation of old Yams options to new MG-SurfOpt options
if style == "0" :
self.commande+= " --optimisation only"
self.commande+=" --in " + self.fichierIn
self.commande+=" --out " + self.fichierOut
- print self.commande
+ print(self.commande)
return True
def clean(self):
import logging
import salome
- from geomsmesh import geompy
- from geomsmesh import geomPublish
- from geomsmesh import geomPublishInFather
- import initLog
+ from .geomsmesh import geompy
+ from .geomsmesh import geomPublish
+ from .geomsmesh import geomPublishInFather
+ from . import initLog
import GEOM
- from geomsmesh import smesh
+ from .geomsmesh import smesh
from salome.smesh import smeshBuilder
import SMESH
import math
# from produitMixte import produitMixte
# from findWireEndVertices import findWireEndVertices
#from findWireIntermediateVertices import findWireIntermediateVertices
- from orderEdgesFromWire import orderEdgesFromWire
+ from .orderEdgesFromWire import orderEdgesFromWire
# from getSubshapeIds import getSubshapeIds
- from putName import putName
+ from .putName import putName
# from distance2 import distance2
- from enleveDefaut import enleveDefaut
- from shapeSurFissure import shapeSurFissure
- from regroupeSainEtDefaut import RegroupeSainEtDefaut
- from triedreBase import triedreBase
+ from .enleveDefaut import enleveDefaut
+ from .shapeSurFissure import shapeSurFissure
+ from .regroupeSainEtDefaut import RegroupeSainEtDefaut
+ from .triedreBase import triedreBase
# from checkDecoupePartition import checkDecoupePartition
# from whichSide import whichSide
# from whichSideMulti import whichSideMulti
#from whichSideVertex import whichSideVertex
#from projettePointSurCourbe import projettePointSurCourbe
# from prolongeWire import prolongeWire
- from restreintFaceFissure import restreintFaceFissure
- from partitionneFissureParPipe import partitionneFissureParPipe
- from construitPartitionsPeauFissure import construitPartitionsPeauFissure
- from compoundFromList import compoundFromList
- from identifieElementsGeometriquesPeau import identifieElementsGeometriquesPeau
- from identifieFacesEdgesFissureExterne import identifieFacesEdgesFissureExterne
- from calculePointsAxiauxPipe import calculePointsAxiauxPipe
- from elimineExtremitesPipe import elimineExtremitesPipe
- from construitEdgesRadialesDebouchantes import construitEdgesRadialesDebouchantes
- from creePointsPipePeau import creePointsPipePeau
- from ajustePointsEdgePipeFissure import ajustePointsEdgePipeFissure
- from construitMaillagePipe import construitMaillagePipe
- from mailleAretesEtJonction import mailleAretesEtJonction
- from mailleFacesFissure import mailleFacesFissure
- from mailleFacesPeau import mailleFacesPeau
- from fissError import fissError
+ from .restreintFaceFissure import restreintFaceFissure
+ from .partitionneFissureParPipe import partitionneFissureParPipe
+ from .construitPartitionsPeauFissure import construitPartitionsPeauFissure
+ from .compoundFromList import compoundFromList
+ from .identifieElementsGeometriquesPeau import identifieElementsGeometriquesPeau
+ from .identifieFacesEdgesFissureExterne import identifieFacesEdgesFissureExterne
+ from .calculePointsAxiauxPipe import calculePointsAxiauxPipe
+ from .elimineExtremitesPipe import elimineExtremitesPipe
+ from .construitEdgesRadialesDebouchantes import construitEdgesRadialesDebouchantes
+ from .creePointsPipePeau import creePointsPipePeau
+ from .ajustePointsEdgePipeFissure import ajustePointsEdgePipeFissure
+ from .construitMaillagePipe import construitMaillagePipe
+ from .mailleAretesEtJonction import mailleAretesEtJonction
+ from .mailleFacesFissure import mailleFacesFissure
+ from .mailleFacesPeau import mailleFacesPeau
+ from .fissError import fissError
# -----------------------------------------------------------------------------
# --- procédure complète fissure générale
fondFiss = shapesFissure[4] # groupe d'edges de fond de fissure
rayonPipe = shapeFissureParams['rayonPipe']
- if shapeFissureParams.has_key('lenSegPipe'):
+ if 'lenSegPipe' in shapeFissureParams:
lenSegPipe = shapeFissureParams['lenSegPipe']
else:
lenSegPipe = rayonPipe
nbsegCercle = maillageFissureParams['nbsegCercle'] # nombre de secteur dans un cercle du pipe
areteFaceFissure = maillageFissureParams['areteFaceFissure']
lgAretesVives = 0
- if maillageFissureParams.has_key('aretesVives'):
+ if 'aretesVives' in maillageFissureParams:
lgAretesVives = maillageFissureParams['aretesVives']
pointIn_x = 0.0
pointIn_y = 0.0
pointIn_z = 0.0
isPointInterne = False
- if shapeFissureParams.has_key('pointIn_x'):
+ if 'pointIn_x' in shapeFissureParams:
pointIn_x = shapeFissureParams['pointIn_x']
isPointInterne = True
- if shapeFissureParams.has_key('pointIn_y'):
+ if 'pointIn_y' in shapeFissureParams:
pointIn_y = shapeFissureParams['pointIn_y']
isPointInterne = True
- if shapeFissureParams.has_key('pointIn_z'):
+ if 'pointIn_z' in shapeFissureParams:
pointIn_z = shapeFissureParams['pointIn_z']
isPointInterne = True
if isPointInterne:
logging.info("fichier maillage fissure %s", fichierMaillageFissure)
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(True)
+ salome.sg.updateObjBrowser()
logging.info("maillage fissure fini")
# -*- coding: utf-8 -*-
import logging
- from geomsmesh import smesh
+ from .geomsmesh import smesh
import SMESH
import SALOMEDS
- from creeZoneDefautMaillage import creeZoneDefautMaillage
- from peauInterne import peauInterne
- from quadranglesToShapeNoCorner import quadranglesToShapeNoCorner
- from creeZoneDefautFilling import creeZoneDefautFilling
- from creeZoneDefautGeom import creeZoneDefautGeom
- from getCentreFondFiss import getCentreFondFiss
+ from .creeZoneDefautMaillage import creeZoneDefautMaillage
+ from .peauInterne import peauInterne
+ from .quadranglesToShapeNoCorner import quadranglesToShapeNoCorner
+ from .creeZoneDefautFilling import creeZoneDefautFilling
+ from .creeZoneDefautGeom import creeZoneDefautGeom
+ from .getCentreFondFiss import getCentreFondFiss
# -----------------------------------------------------------------------------
# ---
#TODO: a compléter
"""
logging.info('start')
-
- #smesh.SetCurrentStudy(salome.myStudy)
geometrieSaine = geometriesSaines[0]
maillageSain = maillagesSains[0]
coordsNoeudsFissure = shapesFissure[3]
isElliptique = False
- if shapeFissureParams.has_key('elliptique'):
+ if 'elliptique' in shapeFissureParams:
isElliptique = shapeFissureParams['elliptique']
if isElliptique:
- if shapeFissureParams.has_key('demiGrandAxe'):
+ if 'demiGrandAxe' in shapeFissureParams:
demiGrandAxe = shapeFissureParams['demiGrandAxe']
else:
demiGrandAxe = shapeFissureParams['longueur']
for face in facesDefaut:
bordsPartages.append([None,None]) # TODO : traitement des arêtes vives ?
fillconts = facesDefaut
- idFilToCont = range(len(facesDefaut))
+ idFilToCont = list(range(len(facesDefaut)))
return [facesDefaut, centresDefaut, normalsDefaut, extrusionsDefaut, dmoyen, bordsPartages, fillconts, idFilToCont,
maillageSain, internalBoundary, zoneDefaut, zoneDefaut_skin, zoneDefaut_internalFaces, zoneDefaut_internalEdges,
import logging
#logging.info('start')
- import initLog
+ from . import initLog
import salome
salome.salome_init()
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
# logging.debug("initialisation de geompy et smesh OK")
import logging
import salome
- from geomsmesh import geompy
- from geomsmesh import geomPublish
- from geomsmesh import geomPublishInFather
- import initLog
- from geomsmesh import smesh
+ from .geomsmesh import geompy
+ from .geomsmesh import geomPublish
+ from .geomsmesh import geomPublishInFather
+ from . import initLog
+ from .geomsmesh import smesh
import SMESH
import math
- from partitionBlocDefaut import partitionBlocDefaut
- from facesVolumesToriques import facesVolumesToriques
- from facesCirculaires import facesCirculaires
- from propagateTore import propagateTore
- from sortGeneratrices import sortGeneratrices
- from facesFissure import facesFissure
- from facesToreInBloc import facesToreInBloc
- from shapeSurFissure import shapeSurFissure
- from meshBlocPart import meshBlocPart
- from enleveDefaut import enleveDefaut
- from regroupeSainEtDefaut import RegroupeSainEtDefaut
- from putName import putName
+ from .partitionBlocDefaut import partitionBlocDefaut
+ from .facesVolumesToriques import facesVolumesToriques
+ from .facesCirculaires import facesCirculaires
+ from .propagateTore import propagateTore
+ from .sortGeneratrices import sortGeneratrices
+ from .facesFissure import facesFissure
+ from .facesToreInBloc import facesToreInBloc
+ from .shapeSurFissure import shapeSurFissure
+ from .meshBlocPart import meshBlocPart
+ from .enleveDefaut import enleveDefaut
+ from .regroupeSainEtDefaut import RegroupeSainEtDefaut
+ from .putName import putName
# -----------------------------------------------------------------------------
# --- procedure complete fissure elliptique
logging.info("fichier maillage fissure : %s", fichierMaillageFissure)
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(True)
+ salome.sg.updateObjBrowser()
return maillageComplet
import logging
import salome
- from geomsmesh import geompy
- from geomsmesh import geomPublish
- from geomsmesh import geomPublishInFather
- import initLog
+ from .geomsmesh import geompy
+ from .geomsmesh import geomPublish
+ from .geomsmesh import geomPublishInFather
+ from . import initLog
import GEOM
- from geomsmesh import smesh
+ from .geomsmesh import smesh
from salome.smesh import smeshBuilder
import SMESH
import math
import bisect
- from extractionOrientee import extractionOrientee
- from extractionOrienteeMulti import extractionOrienteeMulti
- from sortFaces import sortFaces
- from sortEdges import sortEdges
- from eliminateDoubles import eliminateDoubles
- from substractSubShapes import substractSubShapes
- from produitMixte import produitMixte
- from findWireEndVertices import findWireEndVertices
- from findWireIntermediateVertices import findWireIntermediateVertices
- from orderEdgesFromWire import orderEdgesFromWire
- from getSubshapeIds import getSubshapeIds
- from putName import putName
- from distance2 import distance2
- from enleveDefaut import enleveDefaut
- from shapeSurFissure import shapeSurFissure
- from regroupeSainEtDefaut import RegroupeSainEtDefaut
- from triedreBase import triedreBase
- from checkDecoupePartition import checkDecoupePartition
- from whichSide import whichSide
- from whichSideMulti import whichSideMulti
- from whichSideVertex import whichSideVertex
- from projettePointSurCourbe import projettePointSurCourbe
- from prolongeWire import prolongeWire
+ from .extractionOrientee import extractionOrientee
+ from .extractionOrienteeMulti import extractionOrienteeMulti
+ from .sortFaces import sortFaces
+ from .sortEdges import sortEdges
+ from .eliminateDoubles import eliminateDoubles
+ from .substractSubShapes import substractSubShapes
+ from .produitMixte import produitMixte
+ from .findWireEndVertices import findWireEndVertices
+ from .findWireIntermediateVertices import findWireIntermediateVertices
+ from .orderEdgesFromWire import orderEdgesFromWire
+ from .getSubshapeIds import getSubshapeIds
+ from .putName import putName
+ from .distance2 import distance2
+ from .enleveDefaut import enleveDefaut
+ from .shapeSurFissure import shapeSurFissure
+ from .regroupeSainEtDefaut import RegroupeSainEtDefaut
+ from .triedreBase import triedreBase
+ from .checkDecoupePartition import checkDecoupePartition
+ from .whichSide import whichSide
+ from .whichSideMulti import whichSideMulti
+ from .whichSideVertex import whichSideVertex
+ from .projettePointSurCourbe import projettePointSurCourbe
+ from .prolongeWire import prolongeWire
#from getCentreFondFiss import getCentreFondFiss
# -----------------------------------------------------------------------------
fondFiss = shapesFissure[4] # groupe d'edges de fond de fissure
rayonPipe = shapeFissureParams['rayonPipe']
- if shapeFissureParams.has_key('lenSegPipe'):
+ if 'lenSegPipe' in shapeFissureParams:
lenSegPipe = shapeFissureParams['lenSegPipe']
else:
lenSegPipe = rayonPipe
pointIn_y = 0.0
pointIn_z = 0.0
isPointInterne = False
- if shapeFissureParams.has_key('pointIn_x'):
+ if 'pointIn_x' in shapeFissureParams:
pointIn_x = shapeFissureParams['pointIn_x']
isPointInterne = True
- if shapeFissureParams.has_key('pointIn_y'):
+ if 'pointIn_y' in shapeFissureParams:
pointIn_y = shapeFissureParams['pointIn_y']
isPointInterne = True
- if shapeFissureParams.has_key('pointIn_z'):
+ if 'pointIn_z' in shapeFissureParams:
pointIn_z = shapeFissureParams['pointIn_z']
isPointInterne = True
if isPointInterne:
logging.info("fichier maillage fissure %s", fichierMaillageFissure)
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(True)
+ salome.sg.updateObjBrowser()
logging.info("maillage fissure fini")
import logging
import salome
- from geomsmesh import geompy
- from geomsmesh import geomPublish
- from geomsmesh import geomPublishInFather
- import initLog
- from geomsmesh import smesh
+ from .geomsmesh import geompy
+ from .geomsmesh import geomPublish
+ from .geomsmesh import geomPublishInFather
+ from . import initLog
+ from .geomsmesh import smesh
from salome.smesh import smeshBuilder
import SMESH
import math
- from extractionOrientee import extractionOrientee
- from sortFaces import sortFaces
- from sortEdges import sortEdges
- from eliminateDoubles import eliminateDoubles
- from substractSubShapes import substractSubShapes
- from produitMixte import produitMixte
- from findWireEndVertices import findWireEndVertices
- from getSubshapeIds import getSubshapeIds
- from putName import putName
- from distance2 import distance2
- from enleveDefaut import enleveDefaut
- from shapeSurFissure import shapeSurFissure
- from regroupeSainEtDefaut import RegroupeSainEtDefaut
- from triedreBase import triedreBase
+ from .extractionOrientee import extractionOrientee
+ from .sortFaces import sortFaces
+ from .sortEdges import sortEdges
+ from .eliminateDoubles import eliminateDoubles
+ from .substractSubShapes import substractSubShapes
+ from .produitMixte import produitMixte
+ from .findWireEndVertices import findWireEndVertices
+ from .getSubshapeIds import getSubshapeIds
+ from .putName import putName
+ from .distance2 import distance2
+ from .enleveDefaut import enleveDefaut
+ from .shapeSurFissure import shapeSurFissure
+ from .regroupeSainEtDefaut import RegroupeSainEtDefaut
+ from .triedreBase import triedreBase
# -----------------------------------------------------------------------------
# --- procedure complete fissure longue
logging.info("fichier maillage fissure %s", fichierMaillageFissure)
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(True)
+ salome.sg.updateObjBrowser()
return maillageComplet
# if you already have plugins defined in a salome_plugins.py file, add this file at the end.
# if not, copy this file as ${HOME}/Plugins/smesh_plugins.py or ${APPLI}/Plugins/smesh_plugins.py
- import sys, traceback
import math
+ import sys
+ import traceback
+
from blocFissure import gmu
+
def fissureCoudeDlg(context):
- # get context study, studyId, salomeGui
+ # get context study, salomeGui
study = context.study
- studyId = context.studyId
sg = context.sg
import os
#import subprocess
#import tempfile
from qtsalome import QFileDialog, QMessageBox, QPalette, QColor, QDialog
- from fissureCoude_ui import Ui_Dialog
+ from blocFissure.ihm.fissureCoude_ui import Ui_Dialog
class fissureCoudeDialog(QDialog):
else:
self.ui.sb_nbSecteur.setPalette(self.blackPalette)
- print "incomplet: ", incomplet
+ print("incomplet: ", incomplet)
return incomplet
def fileDefault(self):
filedef = os.path.expanduser("~/.config/salome/dialogFissureCoude.dic")
- print filedef
+ print(filedef)
return filedef
def writeDefault(self, dico):
filedef = self.fileDefault()
- f = open(filedef, 'w')
- f.write(str(dico))
- f.close()
+ with open(filedef, 'w') as f:
+ f.write(str(dico))
def readValPrec(self):
filedef = self.fileDefault()
if os.path.exists(filedef):
- f = open(filedef, 'r')
- txt = f.read()
+ with open(filedef, 'r') as f:
+ txt = f.read()
dico = eval(txt)
- print dico
+ print(dico)
self.initDialog(dico)
def resetVal(self):
self.initDialog(self.defaut)
def sauver(self):
- print "sauver"
+ print("sauver")
fileDiag = QFileDialog(self)
fileDiag.setFileMode(QFileDialog.AnyFile)
fileDiag.setNameFilter("Parametres *.dic (*.dic)")
fileNames = fileDiag.selectedFiles()
filedef = fileNames[0]
dico = self.creeDico()
- f = open(filedef, 'w')
- f.write(str(dico))
- f.close()
+ with open(filedef, 'w') as f:
+ f.write(str(dico))
def recharger(self):
- print "recharger"
+ print("recharger")
fileDiag = QFileDialog(self)
fileDiag.setFileMode(QFileDialog.ExistingFile)
fileDiag.setNameFilter("Parametres *.dic (*.dic)")
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
filedef = fileNames[0]
- print filedef
+ print(filedef)
if os.path.exists(filedef):
- f = open(filedef, 'r')
- txt = f.read()
+ with open(filedef, 'r') as f:
+ txt = f.read()
dico = eval(txt)
- print dico
+ print(dico)
self.initDialog(dico)
def creeDico(self):
aretesFaceFissure = self.ui.dsb_aretesFaceFissure.value(),
influence = self.ui.dsb_influence.value(),
)
- print dico
+ print(dico)
return dico
def checkValues(self):
NOK = self.testval(dico)
if not(NOK):
dico['lenSegPipe'] = (dico['longueur'] + math.pi*dico['profondeur'])/dico['nbTranches']
- print 'lenSegPipe', dico['lenSegPipe']
+ print('lenSegPipe', dico['lenSegPipe'])
areteMinAngle = (dico['rCintr'] -dico['dext']/2.0)*(dico['angle']*math.pi/180.0)/dico['nbAxeCoude']
- print'areteMinAngle', areteMinAngle
+ print('areteMinAngle', areteMinAngle)
areteMinCirco = dico['dext']*math.pi/(2*dico['nbCirconf'])
- print'areteMinCirco', areteMinCirco
+ print('areteMinCirco', areteMinCirco)
areteMinEpais = dico['epais']/dico['nbEpaisseur']
- print'areteMinEpais', areteMinEpais
+ print('areteMinEpais', areteMinEpais)
if dico['influence'] == 0:
dico['influence'] = max(areteMinAngle, areteMinCirco, areteMinEpais)
- print 'influence', dico['influence']
+ print('influence', dico['influence'])
if dico['aretesFaceFissure'] == 0:
dico['aretesFaceFissure'] = (areteMinAngle + areteMinCirco)/2.0
- print 'aretesFaceFissure', dico['aretesFaceFissure']
+ print('aretesFaceFissure', dico['aretesFaceFissure'])
if dico['rbPosiAngul'] == False:
rmoy = (dico['dext'] - dico['epais'])/2.0
eta = 1
if dico['rbFissExt'] == False:
eta = -1
dico['posiAngul'] = (180.0/math.pi)*dico['absCurv']/(dico['rCintr']+(rmoy+eta*dico['epais']/2.0)*math.cos(math.pi*dico['azimut']/180.))
- print 'posiAngul' , dico['posiAngul']
+ print('posiAngul' , dico['posiAngul'])
self.writeDefault(dico)
self.ui.lb_calcul.show()
result = window.result()
if result:
# dialog accepted
- print "dialog accepted, check"
+ print("dialog accepted, check")
retry = window.checkValues()
else:
- print "dialog rejected, exit"
+ print("dialog rejected, exit")
pass
from blocFissure import gmu
def fissureGeneraleDlg(context):
- # get context study, studyId, salomeGui
+ # get context study, salomeGui
study = context.study
- studyId = context.studyId
sg = context.sg
import os
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtGui import QPalette
from PyQt5.QtGui import QColor
- from fissureGenerale_ui import Ui_Dialog
+ from blocFissure.ihm.fissureGenerale_ui import Ui_Dialog
class fissureGeneraleDialog(QtWidgets.QDialog):
def __init__(self):
- print "__init__"
+ print("__init__")
QtWidgets.QDialog.__init__(self)
# Set up the user interface from Designer.
self.ui = Ui_Dialog()
self.ui.sb_couronnes.setValue(dico['nbSegRad'])
self.ui.sb_secteurs.setValue(dico['nbSegCercle'])
self.ui.dsb_areteFaceFissure.setValue(dico['areteFaceFissure'])
- if dico.has_key('aretesVives'):
+ if 'aretesVives' in dico:
self.ui.dsb_aretesVives.setValue(dico['aretesVives'])
else:
self.ui.dsb_aretesVives.setValue(0)
l = dico['edgeFissIds']
for i in l:
if not isinstance(i, int):
- print"not isinstance(i, int)"
+ print("not isinstance(i, int)")
incomplet = True
edgeFissIdsOK=False
break
except:
- print "except eval"
+ print("except eval")
incomplet = True
edgeFissIdsOK=False
if edgeFissIdsOK:
else:
self.ui.dsb_areteFaceFissure.setPalette(self.blackPalette)
- print "incomplet: ", incomplet
+ print("incomplet: ", incomplet)
return incomplet
def fileDefault(self):
filedef = os.path.expanduser("~/.config/salome/dialogFissureGenerale.dic")
- print filedef
+ print(filedef)
return filedef
def writeDefault(self, dico):
filedef = self.fileDefault()
- f = open(filedef, 'w')
- f.write(str(dico))
- f.close()
+ with open(filedef, 'w') as f:
+ f.write(str(dico))
def genereExemples(self):
maillageSain = os.path.join(gmu.pathBloc, 'materielCasTests/CubeAngle.med')
def readValPrec(self):
filedef = self.fileDefault()
if os.path.exists(filedef):
- f = open(filedef, 'r')
- txt = f.read()
+ with open(filedef, 'r') as f:
+ txt = f.read()
dico = eval(txt)
- print dico
+ print(dico)
self.initDialog(dico)
def resetVal(self):
def setLogVerbosity(self, logfile):
from blocFissure.gmu import initLog # le mode de log s'initialise une seule fois
- print "setLogVerbosity"
+ print("setLogVerbosity")
index = self.ui.cb_log.currentIndex()
- print index
+ print(index)
if index == 0:
initLog.setRelease(logfile)
elif index == 1:
def sauver(self):
- print "sauver"
+ print("sauver")
fileDiag = QFileDialog(self)
fileDiag.setFileMode(QFileDialog.AnyFile)
fileDiag.setNameFilter("Parametres *.dic (*.dic)")
fileDiag.setViewMode(QFileDialog.List)
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
- print fileNames
+ print(fileNames)
filedef = fileNames[0]
if filedef[-4:] not in ['.dic']:
filedef += '.dic'
dico = self.creeDico()
- f = open(filedef, 'w')
- f.write(str(dico))
- f.close()
+ with open(filedef, 'w') as f:
+ f.write(str(dico))
def recharger(self):
- print "recharger"
+ print("recharger")
fileDiag = QFileDialog(self)
fileDiag.setFileMode(QFileDialog.ExistingFile)
fileDiag.setNameFilter("Parametres *.dic (*.dic)")
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
filedef = fileNames[0]
- print filedef
+ print(filedef)
if os.path.exists(filedef):
- f = open(filedef, 'r')
- txt = f.read()
+ with open(filedef, 'r') as f:
+ txt = f.read()
dico = eval(txt)
- print dico
+ print(dico)
self.initDialog(dico)
def selectMaillage(self):
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
filedef = fileNames[0]
- print filedef
+ print(filedef)
self.ui.le_maillage.setText(filedef)
def selectFacefiss(self):
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
filedef = fileNames[0]
- print filedef
+ print(filedef)
self.ui.le_facefiss.setText(filedef)
def selectReptrav(self):
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
reptrav = str(fileNames[0])
- print "reptrav ", reptrav
+ print("reptrav ", reptrav)
self.ui.le_reptrav.setText(os.path.abspath(reptrav))
if fileDiag.exec_() :
fileNames = fileDiag.selectedFiles()
tempnom = os.path.split(str(fileNames[0]))[1]
- print "nomres ", tempnom
+ print("nomres ", tempnom)
self.ui.le_nomres.setText(tempnom)
else:
self.ui.le_nomres.setText(nomres)
nomres = str(self.ui.le_nomres.text()),
verbosite = self.ui.cb_log.currentIndex()
)
- print dico
+ print(dico)
return dico
def checkValues(self):
return self.NOK
def execute(self):
- print "execute"
+ print("execute")
dico = self.creeDico()
NOK = self.testval(dico)
if not(NOK):
try:
execInstance = casStandard(dico)
except fissError as erreur:
- print '-'*60
- print type(erreur)
- print '-'*60
- print erreur.msg
- print '-'*60
+ print('-'*60)
+ print(type(erreur))
+ print('-'*60)
+ print(erreur.msg)
+ print('-'*60)
for ligne in erreur.pile:
- print repr(ligne)
- print '-'*60
+ print(repr(ligne))
+ print('-'*60)
texte = erreur.msg
# texte += +"<br>" +'-'*60 +"<br>"
# for ligne in erreur.pile:
# ----------------------------------------------------------------------------
- print "main"
+ print("main")
window = fissureGeneraleDialog()
retry = True
while(retry):
result = window.result()
if result:
# dialog accepted
- print "dialog accepted, check"
+ print("dialog accepted, check")
retry = window.checkValues()
else:
- print "dialog rejected, exit"
+ print("dialog rejected, exit")
pass
- #!/usr/bin/env python
+ #!/usr/bin/env python3
# Copyright (C) 2011-2016 EDF R&D
#
# This library is free software; you can redistribute it and/or
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
+ import csv
import salome
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
filename="/home/gboulant/development/projets/salome/SPADDER/spadder/resources/padderexe/REF_spheres.dat.xyz"
- file=open(filename,'rb')
- import csv
- datalines = csv.reader(file, delimiter=' ')
+ with open(filename,'rb') as f:
+ datalines = csv.reader(file, delimiter=' ')
i=0
for row in datalines:
x=float(row[0])
from qtsalome import QIcon, QStandardItemModel, QStandardItem, QMessageBox, pyqtSignal
- from inputframe_ui import Ui_InputFrame
- from inputdata import InputData
+ from salome.smesh.spadder.gui.inputframe_ui import Ui_InputFrame
+ from salome.smesh.spadder.gui.inputdata import InputData
DEBUG_MODE=True
GROUPNAME_MAXLENGTH=8
self.__selectedMesh = None
return
- self.smeshStudyTool.updateStudy(studyedit.getActiveStudyId())
+ self.smeshStudyTool.updateStudy()
self.__selectedMesh = self.smeshStudyTool.getMeshObjectFromSObject(mySObject)
if CORBA.is_nil(self.__selectedMesh):
self.__ui.txtSmeshObject.setText("The selected object is not a mesh")
"""
# if the entry already exists, we remove it to replace by a
# new one
- if self.__dictInputFiles.has_key(meshName):
+ if meshName in self.__dictInputFiles:
self.__delInputFromMap(meshName)
inputData = InputData()
else:
self.__nbSteelbarMesh += 1
- print inputData
- print "meshType = ",inputData.meshType
- print "nb concrete mesh ",self.__nbConcreteMesh
- print "nb steelbar mesh ",self.__nbSteelbarMesh
+ print(inputData)
+ print("meshType = ",inputData.meshType)
+ print("nb concrete mesh ",self.__nbConcreteMesh)
+ print("nb steelbar mesh ",self.__nbSteelbarMesh)
def onDeleteInput(self):
else:
self.__nbSteelbarMesh -= 1
- print inputData
- print "nb concrete mesh ",self.__nbConcreteMesh
- print "nb steelbar mesh ",self.__nbSteelbarMesh
+ print(inputData)
+ print("nb concrete mesh ",self.__nbConcreteMesh)
+ print("nb steelbar mesh ",self.__nbSteelbarMesh)
def setData(self, dictInputData={}):
the specified data list.
"""
self.clear()
- if dictInputData.has_key(INPUTDATA_KEY_FILES):
+ if INPUTDATA_KEY_FILES in dictInputData:
listInputData = dictInputData["meshfiles"]
for inputData in listInputData:
- meshName = inputData.meshName
+ meshName = inputData.meshName
meshObject = inputData.meshObject
- meshType = inputData.meshType
- groupName = inputData.groupName
+ meshType = inputData.meshType
+ groupName = inputData.groupName
self.__addInputInGui(meshName, meshObject, meshType, groupName)
self.__addInputInMap(meshName, meshObject, meshType, groupName)
if not DEBUG_MODE:
self.onSelectSmeshObject()
- if dictInputData.has_key(INPUTDATA_KEY_PARAM):
- dictInputParameters = dictInputData[INPUTDATA_KEY_PARAM]
- if dictInputParameters.has_key(PARAM_KEY_NBITER):
+ if INPUTDATA_KEY_PARAM in dictInputData:
+ dictInputParameters = dictInputData[INPUTDATA_KEY_PARAM]
+ if PARAM_KEY_NBITER in dictInputParameters:
self.__ui.txtParamNbIter.setValue(dictInputParameters[PARAM_KEY_NBITER])
- if dictInputParameters.has_key(PARAM_KEY_RMAXRMIN):
- self.__ui.txtParamRmaxRmin.setValue(dictInputParameters[PARAM_KEY_RMAXRMIN])
+ if PARAM_KEY_RMAXRMIN in dictInputParameters:
+ self.__ui.txtParamRminRmax.setValue(dictInputParameters[PARAM_KEY_RMAXRMIN])
def getData(self):
"""
dlg=InputDialog()
dlg.displayAndWait()
if dlg.wasOk():
- print "OK has been pressed"
+ print("OK has been pressed")
def TEST_InputDialog_setData():
import sys
dlg=InputDialog()
- from inputdata import InputData
+ from .inputdata import InputData
inputData = InputData()
inputData.meshName = "myMesh"
inputData.meshObject = None
dlg.displayAndWait()
if dlg.wasOk():
- print "OK has been pressed"
+ print("OK has been pressed")
outputListInputData = dlg.getData2()
- print outputListInputData
+ print(outputListInputData)
if __name__ == "__main__":
from qtsalome import QDialog, QIcon, Qt
- from plugindialog_ui import Ui_PluginDialog
- from inputdialog import InputDialog, INPUTDATA_KEY_FILES, INPUTDATA_KEY_PARAM
- from inputdialog import PARAM_KEY_NBITER, PARAM_KEY_RMAXRMIN
- from inputdata import InputData
+ from salome.smesh.spadder.gui.plugindialog_ui import Ui_PluginDialog
+ from salome.smesh.spadder.gui.inputdialog import InputDialog, INPUTDATA_KEY_FILES, INPUTDATA_KEY_PARAM
+ from salome.smesh.spadder.gui.inputdialog import PARAM_KEY_NBITER, PARAM_KEY_RMAXRMIN
+ from salome.smesh.spadder.gui.inputdata import InputData
# __GBO__: uncomment this line and comment the previous one to use the
# demo input dialog instead of the real one.
#from demoinputdialog import InputDialog
from omniORB import CORBA
import SMESH
from salome.smesh import smeshBuilder
-smesh = smeshBuilder.New(salome.myStudy)
+smesh = smeshBuilder.New()
import MESHJOB
gui_states = ["CAN_SELECT", "CAN_COMPUTE", "CAN_REFRESH", "CAN_PUBLISH"]
self.__ui.btnClear.setIcon(icon)
# Then, we can connect the slot to there associated button event
- self.__ui.btnInput.clicked.connect( self.onInput )
+ self.__ui.btnInput.clicked.connect( self.onInput )
self.__ui.btnCompute.clicked.connect( self.onCompute )
self.__ui.btnRefresh.clicked.connect( self.onRefresh )
self.__ui.btnPublish.clicked.connect( self.onPublish )
self.__inputDialog.windowFlags() | Qt.WindowStaysOnTopHint)
# The signal inputValidated emitted from inputDialog is
# connected to the slot function onProcessInput:
- self.__inputDialog.inputValidated.connect( self.onProcessInput )
+ self.__inputDialog.inputValidated.connect( self.onProcessInput )
else:
self.__ui.frameInput.setVisible(True)
servant. Note that the component is loaded on first demand,
and then the reference is recycled.
"""
- if self.__dict__.has_key("__jobManager") and self.__jobManager is not None:
+ if "__jobManager" in self.__dict__ and self.__jobManager is not None:
return self.__jobManager
# WARN: we first have to update the SALOME components catalog
# And to create a list of the additional parameters.
# WARN: the CORBA interface requires string values.
meshJobParameterList=[]
- for inputParameterKey in self.__dictInputParameters.keys():
+ for inputParameterKey in self.__dictInputParameters:
value = self.__dictInputParameters[inputParameterKey]
parameter = MESHJOB.MeshJobParameter(name=inputParameterKey,value=str(value))
meshJobParameterList.append(parameter)
medfilename = os.path.join(meshJobResults.results_dirname,
meshJobResults.outputmesh_filename)
- smesh.SetCurrentStudy(studyedit.getActiveStudy())
+ smesh.UpdateStudy()
([outputMesh], status) = smesh.CreateMeshesFromMED(medfilename)
# By convention, the name of the output mesh in the study is
meshname = 'padder_'+str(self.__jobid)
smesh.SetName(outputMesh.GetMesh(), meshname)
if salome.sg.hasDesktop():
- salome.sg.updateObjBrowser(False)
+ salome.sg.updateObjBrowser()
self.__ui.lblStatusBar.setText("Publication OK")
self.__setGuiState(["CAN_SELECT"])
if __name__ == "__main__":
TEST_PluginDialog()
-
-
-
spadder.loadSpadderCatalog()
# Basic test
- print "Basic tests"
+ print("Basic tests")
c=salome.lcc.FindOrLoadComponent("FactoryServer","SPADDERPluginTester")
z=c.demo(2.,3.)
# Test of usage of KERNEL services from the test component
- print "Test of usage of KERNEL services from the test component"
+ print("Test of usage of KERNEL services from the test component")
c.testkernel()
# Test of usage of SMESH engine from the test component
# WARN: the SMESH engine must be loaded first
- print "Test of usage of SMESH engine from the test component"
+ print("Test of usage of SMESH engine from the test component")
import SMESH
salome.lcc.FindOrLoadComponent("FactoryServer","SMESH")
-c.testsmesh(salome.myStudyId)
+c.testsmesh()
- print "Test completed : OK"
+ print("Test completed : OK")