python_version="python%d.%d" % sys.version_info[0:2]
- if not os.environ.has_key("SALOME_StdMeshersResources"):
+ if "SALOME_StdMeshersResources" not in os.environ:
os.environ["SALOME_StdMeshersResources"] \
= os.path.join(os.environ["SMESH_ROOT_DIR"],"share",salome_subdir,"resources","smesh")
pass
# find plugins
plugin_list = ["StdMeshers"]
resource_path_list = []
- for env_var in os.environ.keys():
+ for env_var in list(os.environ.keys()):
value = os.environ[env_var]
if env_var[-9:] == "_ROOT_DIR" and value:
plugin_root = value
# add paths of plugin
plugin_list.append(plugin)
- if not os.environ.has_key("SALOME_"+plugin+"Resources"):
+ if "SALOME_"+plugin+"Resources" not in os.environ:
resource_path = os.path.join(plugin_root,"share",salome_subdir,"resources",plugin.lower())
os.environ["SALOME_"+plugin+"Resources"] = resource_path
resource_path_list.append( resource_path )
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())
# 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
# 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())
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
# 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 )
# 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")
# create mesh
from SMESH_mechanic import *
-print
+print()
# create a group of all faces (quadrangles) generated on sub_face3
quads_on_face3 = mesh.MakeGroup("quads_on_face3", SMESH.FACE, SMESH.FT_BelongToGeom,'=',sub_face3)
-print "There are %s quadrangles generated on '%s' and included in the group '%s'" % ( quads_on_face3.Size(), sub_face3.GetName(), quads_on_face3.GetName() )
+print("There are %s quadrangles generated on '%s' and included in the group '%s'" % ( quads_on_face3.Size(), sub_face3.GetName(), quads_on_face3.GetName() ))
# create a group of all the rest quadrangles, generated on other faces by combining 2 criteria:
# - negated FT_BelongToMeshGroup to select elements not included in quads_on_face3
quadrangles = smesh.GetCriterion( SMESH.FACE, SMESH.FT_ElemGeomType,'=',SMESH.Geom_QUADRANGLE )
rest_quads = mesh.MakeGroupByCriteria("rest_quads", [ not_on_face3, quadrangles ])
-print "'%s' group includes all the rest %s quadrangles" % ( rest_quads.GetName(), rest_quads.Size() )
+print("'%s' group includes all the rest %s quadrangles" % ( rest_quads.GetName(), rest_quads.Size() ))
# get faces with aspect ratio > 2.5
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_AspectRatio, SMESH.FT_MoreThan, 2.5)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with aspect ratio > 2.5:", len(ids)
+print("Number of faces with aspect ratio > 2.5:", len(ids))
# get faces with aspect ratio > 1.5
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_AspectRatio, '>', 1.5, mesh=mesh)
ids = filter.GetIDs()
-print "Number of faces with aspect ratio > 1.5:", len(ids)
+print("Number of faces with aspect ratio > 1.5:", len(ids))
# copy the faces with aspect ratio > 1.5 to another mesh;
# this demostrates that a filter can be used where usually a group or sub-mesh is acceptable
filter.SetMesh( mesh.GetMesh() ) # - actually non necessary as mesh is set at filter creation
mesh2 = smesh.CopyMesh( filter, "AR > 1.5" )
-print "Number of copied faces with aspect ratio > 1.5:", mesh2.NbFaces()
+print("Number of copied faces with aspect ratio > 1.5:", mesh2.NbFaces())
# create a group (Group on Filter) of faces with Aspect Ratio < 1.5
group = mesh.MakeGroup("AR < 1.5", SMESH.FACE, SMESH.FT_AspectRatio, '<', 1.5)
-print "Number of faces with aspect ratio < 1.5:", group.Size()
+print("Number of faces with aspect ratio < 1.5:", group.Size())
# combine several criteria to Create a Group of only Triangular faces with Aspect Ratio < 1.5;
# note that contents of a GroupOnFilter is dynamically updated as the mesh changes
crit = [ smesh.GetCriterion( SMESH.FACE, SMESH.FT_AspectRatio, '<', 1.5, BinaryOp=SMESH.FT_LogicalAND ),
smesh.GetCriterion( SMESH.FACE, SMESH.FT_ElemGeomType,'=', SMESH.Geom_TRIANGLE ) ]
triaGroup = mesh.MakeGroupByCriteria( "Tria AR < 1.5", crit )
-print "Number of triangles with aspect ratio < 1.5:", triaGroup.Size()
+print("Number of triangles with aspect ratio < 1.5:", triaGroup.Size())
# get range of values of Aspect Ratio of all faces in the mesh
aspects = mesh.GetMinMax( SMESH.FT_AspectRatio )
-print "MESH: Min aspect = %s, Max aspect = %s" % ( aspects[0], aspects[1] )
+print("MESH: Min aspect = %s, Max aspect = %s" % ( aspects[0], aspects[1] ))
# get max value of Aspect Ratio of faces in triaGroup
grAspects = mesh.GetMinMax( SMESH.FT_AspectRatio, triaGroup )
-print "GROUP: Max aspect = %s" % grAspects[1]
+print("GROUP: Max aspect = %s" % grAspects[1])
# get Aspect Ratio of an element
aspect = mesh.FunctorValue( SMESH.FT_AspectRatio, ids[0] )
-print "Aspect ratio of the face %s = %s" % ( ids[0], aspect )
+print("Aspect ratio of the face %s = %s" % ( ids[0], aspect ))
# get volumes with aspect ratio < 2.0
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_AspectRatio3D, SMESH.FT_LessThan, 2.0)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of volumes with aspect ratio < 2.0:", len(ids)
+print("Number of volumes with aspect ratio < 2.0:", len(ids))
# get faces with warping angle = 2.0e-13 with tolerance 5.0e-14
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_Warping, "=", 2.0e-13, Tolerance=5.0e-14)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with warping angle = 2.0e-13 (tolerance 5.0e-14):", len(ids)
+print("Number of faces with warping angle = 2.0e-13 (tolerance 5.0e-14):", len(ids))
# get faces with minimum angle > 75
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_MinimumAngle,">", 75)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with minimum angle > 75:", len(ids)
+print("Number of faces with minimum angle > 75:", len(ids))
# get faces with taper < 1.e-15
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_Taper, SMESH.FT_LessThan, 1.e-15)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with taper < 1.e-15:", len(ids)
+print("Number of faces with taper < 1.e-15:", len(ids))
# get faces with skew > 50
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_Skew, SMESH.FT_MoreThan, 50)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with skew > 50:", len(ids)
+print("Number of faces with skew > 50:", len(ids))
criterion2 = smesh.GetCriterion(SMESH.FACE, SMESH.FT_Area, SMESH.FT_LessThan, 90)
filter = smesh.GetFilterFromCriteria([criterion1,criterion2], SMESH.FT_LogicalAND)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with area in range (60,90):", len(ids)
+print("Number of faces with area in range (60,90):", len(ids))
# get volumes faces with volume > 100
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_Volume3D, SMESH.FT_MoreThan, 100)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of volumes with volume > 100:", len(ids)
+print("Number of volumes with volume > 100:", len(ids))
# 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))
# 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))
# get all free nodes
filter = smesh.GetFilter(SMESH.NODE, SMESH.FT_FreeNodes)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of free nodes:", len(ids)
+print("Number of free nodes:", len(ids))
# get all free faces
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_FreeFaces)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of free faces:", len(ids)
+print("Number of free faces:", len(ids))
# get all faces with bare borders
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_BareBorderFace)
ids = mesh.GetIdsFromFilter(filter)
-print "Faces with bare borders:", ids
+print("Faces with bare borders:", ids)
# get all faces co-planar to the first face with tolerance 5 degrees
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_CoplanarFaces,faceID,Tolerance=5.0)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces coplanar with the first one:", len(ids)
+print("Number of faces coplanar with the first one:", len(ids))
# get all over-constrained faces
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_OverConstrainedFace)
ids = mesh.GetIdsFromFilter(filter)
-print "Over-constrained faces:", ids
+print("Over-constrained faces:", ids)
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 )))
# 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 )))
# 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))
# get faces which consist of edges belonging to 2 mesh elements
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_MultiConnection2D, 2)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces consisting of edges belonging to 2 faces:", len(ids)
+print("Number of faces consisting of edges belonging to 2 faces:", len(ids))
# get edges with length > 14
filter = smesh.GetFilter(SMESH.EDGE, SMESH.FT_Length, SMESH.FT_MoreThan, 14)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of edges with length > 14:", len(ids)
+print("Number of edges with length > 14:", len(ids))
# get all faces that have edges with length > 14
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_Length2D, SMESH.FT_MoreThan, 14)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with maximum edge length > 14:", len(ids)
+print("Number of faces with maximum edge length > 14:", len(ids))
# get all faces that have elements with length > 10
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_MaxElementLength2D, SMESH.FT_MoreThan, 10)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces with maximum element length > 10:", len(ids)
+print("Number of faces with maximum element length > 10:", len(ids))
# get all volumes that have elements with length > 10
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_MaxElementLength3D, SMESH.FT_MoreThan, 10)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of volumes with maximum element length > 10:", len(ids)
+print("Number of volumes with maximum element length > 10:", len(ids))
# get all volumes with bare borders
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_BareBorderVolume)
ids = mesh.GetIdsFromFilter(filter)
-print "Volumes with bare borders:", ids
+print("Volumes with bare borders:", ids)
# get all over-constrained volumes
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_OverConstrainedVolume)
ids = mesh.GetIdsFromFilter(filter)
-print "Over-constrained volumes:", ids
+print("Over-constrained volumes:", ids)
# get all faces which nodes lie on the face sub_face3
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_BelongToGeom, sub_face3)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces which nodes lie on sub_face3:", len(ids)
+print("Number of faces which nodes lie on sub_face3:", len(ids))
# get all faces at least one node of each lies on the face sub_face3
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_LyingOnGeom, sub_face3)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces at least one node of each lies on sub_face3:", len(ids)
+print("Number of faces at least one node of each lies on sub_face3:", len(ids))
# get all nodes which lie on the plane \a plane_1
filter = smesh.GetFilter(SMESH.NODE, SMESH.FT_BelongToPlane, plane_1)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of nodes which lie on the plane plane_1:", len(ids)
+print("Number of nodes which lie on the plane plane_1:", len(ids))
# get all faces which lie on the cylindrical face \a sub_face1
filter = smesh.GetFilter(SMESH.FACE, SMESH.FT_BelongToCylinder, sub_face1)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of faces which lie on the cylindrical surface sub_face1:", len(ids)
+print("Number of faces which lie on the cylindrical surface sub_face1:", len(ids))
# get all nodes which lie on the surface \a surface_1
filter = smesh.GetFilter(SMESH.NODE, SMESH.FT_BelongToGenSurface, surface_1)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of nodes which lie on the surface surface_1:", len(ids)
+print("Number of nodes which lie on the surface surface_1:", len(ids))
filter = smesh.CreateFilterManager().CreateFilter()
filter.SetCriteria([criterion1,criterion2])
ids = mesh.GetIdsFromFilter(filter)
-print "Number of nodes in ranges [5-10] and [15-30]:", len(ids)
+print("Number of nodes in ranges [5-10] and [15-30]:", len(ids))
# get all badly oriented volumes
filter = smesh.GetFilter(SMESH.VOLUME, SMESH.FT_BadOrientedVolume)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of badly oriented volumes:", len(ids)
+print("Number of badly oriented volumes:", len(ids))
filter_quadratic = smesh.GetFilter(SMESH.EDGE, SMESH.FT_LinearOrQuadratic, SMESH.FT_LogicalNOT)
ids_linear = mesh.GetIdsFromFilter(filter_linear)
ids_quadratic = mesh.GetIdsFromFilter(filter_quadratic)
-print "Number of linear edges:", len(ids_linear), "; number of quadratic edges:", len(ids_quadratic)
+print("Number of linear edges:", len(ids_linear), "; number of quadratic edges:", len(ids_quadratic))
# convert mesh to quadratic
-print "Convert to quadratic..."
+print("Convert to quadratic...")
mesh.ConvertToQuadratic()
# get linear and quadratic edges
ids_linear = mesh.GetIdsFromFilter(filter_linear)
ids_quadratic = mesh.GetIdsFromFilter(filter_quadratic)
-print "Number of linear edges:", len(ids_linear), "; number of quadratic edges:", len(ids_quadratic)
+print("Number of linear edges:", len(ids_linear), "; number of quadratic edges:", len(ids_quadratic))
# get number of the edges not belonging to the group with the given color
filter = smesh.GetFilter(SMESH.EDGE, SMESH.FT_GroupColor, c, SMESH.FT_LogicalNOT)
ids = mesh.GetIdsFromFilter(filter)
-print "Number of edges not beloging to the group with color (0.1, 0.5, 1.0):", len(ids)
+print("Number of edges not beloging to the group with color (0.1, 0.5, 1.0):", len(ids))
ids_qua = mesh.GetIdsFromFilter(filter_qua)
ids_tet = mesh.GetIdsFromFilter(filter_tet)
ids_pyr = mesh.GetIdsFromFilter(filter_pyr)
-print "Number of triangles:", len(ids_tri)
-print "Number of quadrangles:", len(ids_qua)
-print "Number of tetrahedrons:", len(ids_tet)
-print "Number of pyramids:", len(ids_pyr)
+print("Number of triangles:", len(ids_tri))
+print("Number of quadrangles:", len(ids_qua))
+print("Number of tetrahedrons:", len(ids_tet))
+print("Number of pyramids:", len(ids_pyr))
# get triangles with 7 nodes
filter_tri = smesh.GetFilter(SMESH.FACE, SMESH.FT_EntityType,'=', SMESH.Entity_BiQuad_Triangle )
ids_tri = mesh.GetIdsFromFilter(filter_tri)
-print "Number of bi-quadratic triangles:", len(ids_tri)
+print("Number of bi-quadratic triangles:", len(ids_tri))
# get balls with diameter > 5.
diam_filter = smesh.GetFilter(SMESH.BALL, SMESH.FT_BallDiameter,'>', 5. )
ids = mesh.GetIdsFromFilter( diam_filter )
-print "Number of balls with diameter > 5:", len(ids)
+print("Number of balls with diameter > 5:", len(ids))
# 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()))
# get nodes connected to more than 6 tetrahedra
conn_nb_filter = smesh.GetFilter(SMESH.NODE, SMESH.FT_NodeConnectivityNumber,'>', 6 )
ids = mesh.GetIdsFromFilter( conn_nb_filter )
-print "Number of nodes connected to more than 6 tetrahedra:", len(ids)
+print("Number of nodes connected to more than 6 tetrahedra:", len(ids))
# 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
]
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)
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)
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)
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)
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)
# 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
# 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")
# 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)
# 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)
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 ))
import SMESH_mechanic
mesh = SMESH_mechanic.mesh
-print ""
+print("")
# add node
n1 = mesh.AddNode(50, 10, 0)
-if n1 == 0: print "KO node addition."
+if n1 == 0: print("KO node addition.")
# add edge
e1 = mesh.AddEdge([n1, 38])
-if e1 == 0: print "KO edge addition."
-else: print "New Edge has been added with ID ", e1
+if e1 == 0: print("KO edge addition.")
+else: print("New Edge has been added with ID ", e1)
import SMESH_mechanic
mesh = SMESH_mechanic.mesh
-print ""
+print("")
# add node
n1 = mesh.AddNode(50, 10, 0)
-if n1 == 0: print "KO node addition."
+if n1 == 0: print("KO node addition.")
# add triangle
t1 = mesh.AddFace([n1, 38, 39])
-if t1 == 0: print "KO triangle addition."
-else: print "New Triangle has been added with ID ", t1
+if t1 == 0: print("KO triangle addition.")
+else: print("New Triangle has been added with ID ", t1)
import SMESH_mechanic
mesh = SMESH_mechanic.mesh
-print ""
+print("")
# add node
n1 = mesh.AddNode(50, 10, 0)
-if n1 == 0: print "KO node addition."
+if n1 == 0: print("KO node addition.")
n2 = mesh.AddNode(40, 20, 0)
-if n2 == 0: print "KO node addition."
+if n2 == 0: print("KO node addition.")
# add quadrangle
q1 = mesh.AddFace([n2, n1, 38, 39])
-if q1 == 0: print "KO quadrangle addition."
-else: print "New Quadrangle has been added with ID ", q1
+if q1 == 0: print("KO quadrangle addition.")
+else: print("New Quadrangle has been added with ID ", q1)
import SMESH_mechanic
mesh = SMESH_mechanic.mesh
-print ""
+print("")
# add node
n1 = mesh.AddNode(50, 10, 0)
-if n1 == 0: print "KO node addition."
+if n1 == 0: print("KO node addition.")
# add tetrahedron
t1 = mesh.AddVolume([n1, 38, 39, 246])
-if t1 == 0: print "KO tetrahedron addition."
-else: print "New Tetrahedron has been added with ID ", t1
+if t1 == 0: print("KO tetrahedron addition.")
+else: print("New Tetrahedron has been added with ID ", t1)
import SMESH_mechanic
mesh = SMESH_mechanic.mesh
-print ""
+print("")
# add nodes
nId1 = mesh.AddNode(50, 10, 0)
nId3 = mesh.AddNode(50, 10, 10)
nId4 = mesh.AddNode(47, 12, 10)
-if nId1 == 0 or nId2 == 0 or nId3 == 0 or nId4 == 0: print "KO node addition."
+if nId1 == 0 or nId2 == 0 or nId3 == 0 or nId4 == 0: print("KO node addition.")
# add hexahedron
vId = mesh.AddVolume([nId2, nId1, 38, 39, nId4, nId3, 245, 246])
-if vId == 0: print "KO Hexahedron addition."
-else: print "New Hexahedron has been added with ID ", vId
+if vId == 0: print("KO Hexahedron addition.")
+else: print("New Hexahedron has been added with ID ", vId)
# remove nodes #246 and #255
res = mesh.RemoveNodes([246, 255])
-if res == 1: print "Nodes removing is OK!"
-else: print "KO nodes removing."
+if res == 1: print("Nodes removing is OK!")
+else: print("KO nodes removing.")
# remove three elements: #850, #859 and #814
res = mesh.RemoveElements([850, 859, 814])
-if res == 1: print "Elements removing is OK!"
-else: print "KO Elements removing."
+if res == 1: print("Elements removing is OK!")
+else: print("KO Elements removing.")
mesh.AddNode(1,1,1)
# remove just created orphan nodes
res = mesh.RemoveOrphanNodes()
-if res == 1: print "Removed %d nodes!" % res
-else: print "KO nodes removing."
+if res == 1: print("Removed %d nodes!" % res)
+else: print("KO nodes removing.")
# 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] ))
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)
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)
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)
# 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)
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
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())
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")
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")
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)
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])
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
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())
# 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)
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
# 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)
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
f.close()
pass
pass
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
pass
pass
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)
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)
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
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-from SMESH_test1 import *
+from .SMESH_test1 import *
## Old style
def CheckBelongToGeomFilterOld(theMeshGen, theMesh, theShape, theSubShape, theElemType):
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
# File : SMESH_GroupFromGeom.py
# Module : SMESH
#
-from SMESH_test1 import *
+from .SMESH_test1 import *
# Compute the mesh created in SMESH_test1
# Project : PAL/SALOME
#==============================================================================
#
-from SMESH_test1 import *
+from .SMESH_test1 import *
# Compute the mesh created in SMESH_test1
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)
aGroup.Add(anIds)
#Example
-from SMESH_test1 import *
+from .SMESH_test1 import *
mesh.Compute()
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)
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)
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)
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)
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)
# Module : SMESH
#
import salome
-import SMESH_mechanic
+from . import SMESH_mechanic
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
# 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 ]
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)):
# ---- 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)
salome.sg.updateObjBrowser(True)
-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)
# Hypothesis and algorithms for the mesh generation are global
#
import salome
-import SMESH_fixation
+from . import SMESH_fixation
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
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)
# ---- 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)
# The new Netgen algorithm is used that discretizes baoundaries itself
#
import salome
-import SMESH_fixation
+from . import SMESH_fixation
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
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)
-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)
# Hypothesis and algorithms for the mesh generation are global
#
import salome
-import SMESH_fixation
+from . import SMESH_fixation
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
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)
# ---- 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)
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 --------------------------------------
# ---- 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)
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)
# -----------------------------------------------------------------------------
-print "-------------------------- mesh"
+print("-------------------------- mesh")
smesh.SetCurrentStudy(salome.myStudy)
# ---- 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)
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)
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
# ---- 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)
# ---- 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)
# ---- 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)
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)
from launchConfigureParser import verbose
-if verbose(): print "============== import SMESH ======================="
+if verbose(): print("============== import SMESH =======================")
import SMESH
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)
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)
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")
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()
# File : SMESH_test2.py
# Module : SMESH
#
-from SMESH_test1 import *
+from .SMESH_test1 import *
# ---- 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)
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)])
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
def LengthNearVertex(self, length, vertex=0, UseExisting=0):
import types
store_geom = self.geom
- if type(vertex) is types.IntType:
+ if type(vertex) is 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 )
# 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.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 ):
import batchmode_salome
import batchmode_geompy
-import batchmode_smesh
+from . import batchmode_smesh
from salome.StdMeshers import StdMeshersBuilder
smesh = batchmode_smesh.smesh
def CreateMesh (theFileName, area, len = None, nbseg = None):
if not(os.path.isfile(theFileName)) or re.search("\.brep$", theFileName) is None :
- print "Incorrect file name !"
+ print("Incorrect file name !")
return
if (len is None) and (nbseg is None):
- print "Define length or number of segments !"
+ print("Define length or number of segments !")
return
if (len is not None) and (nbseg is not None):
- print "Only one Hypothesis (from length and number of segments) can be defined !"
+ print("Only one Hypothesis (from length and number of segments) can be defined !")
return
# ---- SMESH
- print "-------------------------- create mesh"
+ print("-------------------------- create mesh")
mesh = smesh.Mesh(shape_mesh)
- print "-------------------------- create Hypothesis"
+ print("-------------------------- create Hypothesis")
if (len is not None):
- print "-------------------------- LocalLength"
+ print("-------------------------- LocalLength")
algoReg = mesh.Segment()
hypLength1 = algoReg.LocalLength(len)
- print "Hypothesis type : ", hypLength1.GetName()
- print "Hypothesis ID : ", hypLength1.GetId()
- print "Hypothesis Value: ", hypLength1.GetLength()
+ print("Hypothesis type : ", hypLength1.GetName())
+ print("Hypothesis ID : ", hypLength1.GetId())
+ print("Hypothesis Value: ", hypLength1.GetLength())
if (nbseg is not None):
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
algoReg = mesh.Segment()
hypNbSeg1 = algoReg.NumberOfSegments(nbseg)
- print "Hypothesis type : ", hypNbSeg1.GetName()
- print "Hypothesis ID : ", hypNbSeg1.GetId()
- print "Hypothesis Value: ", hypNbSeg1.GetNumberOfSegments()
+ print("Hypothesis type : ", hypNbSeg1.GetName())
+ print("Hypothesis ID : ", hypNbSeg1.GetId())
+ print("Hypothesis Value: ", hypNbSeg1.GetNumberOfSegments())
if (area == "LengthFromEdges"):
- print "-------------------------- LengthFromEdges"
+ print("-------------------------- LengthFromEdges")
algoMef = mesh.Triangle()
hypLengthFromEdges = algoMef.LengthFromEdges(1)
- print "Hypothesis type : ", hypLengthFromEdges.GetName()
- print "Hypothesis ID : ", hypLengthFromEdges.GetId()
- print "LengthFromEdges Mode: ", hypLengthFromEdges.GetMode()
+ print("Hypothesis type : ", hypLengthFromEdges.GetName())
+ print("Hypothesis ID : ", hypLengthFromEdges.GetId())
+ print("LengthFromEdges Mode: ", hypLengthFromEdges.GetMode())
else:
- print "-------------------------- MaxElementArea"
+ print("-------------------------- MaxElementArea")
algoMef = mesh.Triangle()
hypArea1 = algoMef.MaxElementArea(area)
- print "Hypothesis type : ", hypArea1.GetName()
- print "Hypothesis ID : ", hypArea1.GetId()
- print "Hypothesis Value: ", hypArea1.GetMaxElementArea()
+ print("Hypothesis type : ", hypArea1.GetName())
+ print("Hypothesis ID : ", hypArea1.GetId())
+ print("Hypothesis Value: ", hypArea1.GetMaxElementArea())
- print "-------------------------- Regular_1D"
+ print("-------------------------- Regular_1D")
listHyp = algoReg.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
- print "Algo name: ", algoReg.GetName()
- print "Algo ID : ", algoReg.GetId()
+ print("Algo name: ", algoReg.GetName())
+ print("Algo ID : ", algoReg.GetId())
- print "-------------------------- MEFISTO_2D"
+ print("-------------------------- MEFISTO_2D")
listHyp = algoMef.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
- print "Algo name: ", algoMef.GetName()
- print "Algo ID : ", algoMef.GetId()
+ print("Algo name: ", algoMef.GetName())
+ print("Algo ID : ", algoMef.GetId())
# ---- add hypothesis to shape
- print "-------------------------- compute mesh"
+ print("-------------------------- compute mesh")
ret = mesh.Compute()
- print "Compute Mesh .... ",
- print ret
+ print("Compute Mesh .... ", end=' ')
+ print(ret)
log = mesh.GetLog(0); # no erase trace
#for linelog in log:
# print linelog
- print "------------ INFORMATION ABOUT MESH ------------"
+ print("------------ INFORMATION ABOUT MESH ------------")
- 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 nodes : ", mesh.NbNodes())
+ print("Number of edges : ", mesh.NbEdges())
+ print("Number of faces : ", mesh.NbFaces())
+ print("Number of triangles: ", mesh.NbTriangles())
return mesh
myStudyBuilder = myStudy.NewBuilder()
if myStudyBuilder is None:
- raise RuntimeError, " Null myStudyBuilder"
+ raise RuntimeError(" Null myStudyBuilder")
father = myStudy.FindComponent("SMESH")
if father is None:
# Load all examples
# -----------------
#
-import ex01_cube2build
-import ex02_cube2primitive
-import ex03_cube2partition
-import ex04_cube5tetraHexa
-import ex05_hole1build
-import ex06_hole1boolean
-import ex07_hole1partition
-import ex08_hole2build
-import ex09_grid4build
-import ex10_grid4geometry
-import ex11_grid3partition
-import ex12_grid17partition
-import ex13_hole1partial
-import ex14_cyl1holed
-import ex15_cyl2geometry
-import ex16_cyl2complementary
-import ex17_dome1
-import ex18_dome2
-import ex19_sphereINcube
+from . import ex01_cube2build
+from . import ex02_cube2primitive
+from . import ex03_cube2partition
+from . import ex04_cube5tetraHexa
+from . import ex05_hole1build
+from . import ex06_hole1boolean
+from . import ex07_hole1partition
+from . import ex08_hole2build
+from . import ex09_grid4build
+from . import ex10_grid4geometry
+from . import ex11_grid3partition
+from . import ex12_grid17partition
+from . import ex13_hole1partial
+from . import ex14_cyl1holed
+from . import ex15_cyl2geometry
+from . import ex16_cyl2complementary
+from . import ex17_dome1
+from . import ex18_dome2
+from . import ex19_sphereINcube
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)
# ----------
if os.access(results+".xml", os.F_OK):
- print "Ok: tepal"
+ print("Ok: tepal")
else:
- print "KO: tepal"
+ print("KO: tepal")
# Update object browser
# ---------------------
### 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 )
engineSmesh = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
smesh = smeshBuilder.New(salome.myStudy, engineSmesh)
except:
- print "exception in smesh.py: instance creation failed"
+ print("exception in smesh.py: instance creation failed")
smesh = None
pass
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 )
del k
pass
-print """
+print("""
===============================================================================
WARNING:
Usage of smesh.py is deprecated in SALOME V7.2!
It does not work in the second, third, etc studies!
===============================================================================
-"""
+""")
import SALOME
import SALOMEDS
import os
+import collections
## 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 isinstance( args[-1], collections.Callable):
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
# 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):
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 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
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
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])
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
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)
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()
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:
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:
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
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,
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:
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
if not meth_name.startswith("Get") and \
not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
method = getattr ( hyp.__class__, meth_name )
- if callable(method):
+ if isinstance(method, collections.Callable):
setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
return hyp
# 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
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 not isinstance( refresh, list): # not a call from subMesh.Compute()
pass
groups = []
- for algoName, shapes in algo2shapes.items():
+ for algoName, shapes in list(algo2shapes.items()):
while shapes:
groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
otherTypeShapes = []
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
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
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
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,
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 )
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 ))
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__()
if isinstance( arg, str ) and arg:
algoType = arg
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
+ 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:
+ 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 )
## 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
# 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())
#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)
if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
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):
if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
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())
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):
f.write(cmds)
self.make_executable(nomFichier)
- if verbose: print("INFO: MGCleaner launch script file: %s" % nomFichier)
+ if verbose: print(("INFO: MGCleaner launch script file: %s" % nomFichier))
self.monExe.start(nomFichier)
self.monExe.closeWriteChannel()
savedir=os.environ['HOME']
fn = QFileDialog.getSaveFileName(None, self.trUtf8("Save File"),savedir)
if fn.isNull() : return
- ulfile = os.path.abspath(unicode(fn))
+ ulfile = os.path.abspath(str(fn))
try:
f = open(fn, 'wb')
f.write(str(self.TB_Exe.toPlainText()))
f.close()
- except IOError, why:
+ except IOError as why:
QMessageBox.critical(self, self.trUtf8('Save File'),
self.trUtf8('The file <b>%1</b> could not be saved.<br>Reason: %2')
- .arg(unicode(fn)).arg(str(why)))
+ .arg(str(fn)).arg(str(why)))
def readFromStdErr(self):
a=self.monExe.readAllStandardError()
- self.TB_Exe.append(unicode(a.data()))
+ self.TB_Exe.append(str(a.data()))
def readFromStdOut(self) :
a=self.monExe.readAllStandardOutput()
- aa=unicode(a.data())
+ aa=str(a.data())
self.TB_Exe.append(aa)
def finished(self):
RealLocalMeshing = Bloc[0][0].GeoPar[1][0]/Bloc[0][0].DirectionalMeshParams[0]
ExtrusionAngle = 2. * math.asin(RealLocalMeshing/(2*R))*180./math.pi
-print "\nThe mesh will be revolved with an angle of :",ExtrusionAngle
+print("\nThe mesh will be revolved with an angle of :",ExtrusionAngle)
RevolveMesh(SRVMesh, Center=[R+0.01,0,0], Direction=[0,1,0], AngleDeg=ExtrusionAngle, Scale=0.001)
2 : lambda x: "Fatal: Incorrect input \n",
3 : lambda x: "Fatal: Overlapping objects detected \n",
4 : lambda x: "Fatal: Incompatible object type with neighbouring objects" }[code](str(code))
- print MessageString
+ print(MessageString)
#if code > 1 : sys.exit()
return 1
-import sys, math, commands
-CWD = commands.getoutput('pwd')
+import sys, math, subprocess
+CWD = subprocess.getoutput('pwd')
sys.path.append(CWD)
from MacObject import *
# INTRODUCTION HERE
-import sys, math, copy, commands
-CWD = commands.getoutput('pwd')
+import sys, math, copy, subprocess
+CWD = subprocess.getoutput('pwd')
sys.path.append(CWD)
from MacObject import *
ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY )
RemoveLastObj()
- print "ObjIDLists: ", ObjIDLists
+ print("ObjIDLists: ", ObjIDLists)
RealSegments = []
Direction = []
flag = 0
if not(args.__contains__('recursive')) : Config.Count = 0
- print "Config.Count : ", Config.Count
+ print("Config.Count : ", Config.Count)
Config.Criterion = GetCriterion(ObjIDLists)
for index, ObjList in enumerate(ObjIDLists) :
if not (ObjList[0] == -1 or Config.Count >= Config.Criterion):
"""
Output = []
try : Array.index(Element)
- except ValueError : print "No more occurrences"
+ except ValueError : print("No more occurrences")
else : Output.append(Array.index(Element))
if not(Output == []) and len(Array) > 1 :
# INTRODUCTION HERE
-import sys, math, copy, commands
-CWD = commands.getoutput('pwd')
+import sys, math, copy, subprocess
+CWD = subprocess.getoutput('pwd')
sys.path.append(CWD)
from MacObject import *
BoundaryLengths = [IntLen(dummy.DirBoundaries(i)) for i in range(4) ]
# Calculate global mesh element size on each direction
GlobalDelta = [1.*BoundaryLengths[i]/ExistingSegments[i] for i in range(4) ]
- print "GlobalDelta :",GlobalDelta
+ print("GlobalDelta :",GlobalDelta)
# Sort the connection list for the full Box
[(X0,Y0),(DX,DY)] = dummy.GeoPar
ObjIDLists = SortObjLists(Config.Connections[-1],X0 , Y0 , DX , DY )
ToLook2 = [1,0,3,2][index]
RealSegments = Config.ListObj[ObjID].DirectionalMeshParams[ToLook2]*IntLen(CommonSide)/IntLen(Config.ListObj[ObjID].DirBoundaries(ToLook1))
LocalDelta = 1.*IntLen(CommonSide)/RealSegments
- print "Direction:", ["West","East","South","North"][ToLook2]
- print "IntLen(CommonSide):",IntLen(CommonSide)
- print "RealSegments:",RealSegments
- print "LocalDelta:",LocalDelta
+ print("Direction:", ["West","East","South","North"][ToLook2])
+ print("IntLen(CommonSide):",IntLen(CommonSide))
+ print("RealSegments:",RealSegments)
+ print("LocalDelta:",LocalDelta)
if flag and Config.Count < Config.Criterion:
if index ==0 :
if abs(CommonSide[0] - Ymin)<1e-7 : SouthGR = GroupNames[0]
if Config.Count >= Config.Criterion :
break
if flag == 0 and Config.Count < Config.Criterion:
- print "Creating NonOrtho object with the points:", Pt1,Pt2,Pt3,Pt4
+ print("Creating NonOrtho object with the points:", Pt1,Pt2,Pt3,Pt4)
MacObject('NonOrtho',[Pt1,Pt2,Pt3,Pt4] ,['auto'], groups = GroupNames)
Config.Count += 1
def FindCommonSide (Int1, Int2) :
if max(Int1[0],Int2[0])<min(Int1[1],Int2[1]): return [max(Int1[0],Int2[0]), min(Int1[1],Int2[1])]
else :
- print "Can not find interval intersection, returning [0,0]..."
+ print("Can not find interval intersection, returning [0,0]...")
return [0,0]
def IntLen (Interval) :
"""
Output = []
try : Array.index(Element)
- except ValueError : print "No more occurrences"
+ except ValueError : print("No more occurrences")
else : Output.append(Array.index(Element))
if not(Output == []) and len(Array) > 1 :
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
+ InvDictionary = dict((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 = []
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"
+ 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)):
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
+ InvDictionary = dict((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
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"
+ 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)):
# This functions can take a groups input containing the group names of 4 sides in addition to the internal circular boundary
# in the following order : [South,North,West,East,Internal].
-import sys, math, commands
-CWD = commands.getoutput('pwd')
+import sys, math, subprocess
+CWD = subprocess.getoutput('pwd')
sys.path.append(CWD)
# K is the pitch ratio
K = float(D)/(DLocal-D)
- print "A local pitch ratio of K =", K ," will be used. "
+ print("A local pitch ratio of K =", K ," will be used. ")
NumCuts = 2*GenFunctions.QuarCylParam(K)
InternalMeshing = int(math.ceil(math.pi*D/(4*NumCuts*LocalMeshing)))
if InternalMeshing == 0 : InternalMeshing = 1 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
- print "Possible Local meshing is :", math.pi*D/(4*NumCuts*InternalMeshing), "\nThis value is returned by this function for your convenience.\n"
+ print("Possible Local meshing is :", math.pi*D/(4*NumCuts*InternalMeshing), "\nThis value is returned by this function for your convenience.\n")
if args.__contains__('groups') :
GroupNames = args['groups']
else : GroupNames = [None, None, None, None, None]
##########################################################################################################
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)
##########################################################################################################
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,
##########################################################################################################
def BoxAng32 (MacObject):
- if Config.debug : print "Generating sharp angle"
+ if Config.debug : print("Generating sharp angle")
Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
RotAngle = {'NE' : lambda : 0,
'NW' : lambda : math.pi/2,
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)
##########################################################################################################
def CompBoxF (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)
##########################################################################################################
def NonOrtho (MacObject):
- if Config.debug : print "Generating Non-orthogonal quadrangle"
+ if Config.debug : print("Generating Non-orthogonal quadrangle")
RectFace = Quadrangler (MacObject.PtCoor)
##########################################################################################################
def QuartCyl (MacObject):
- if Config.debug : print "Generating quarter cylinder"
+ if Config.debug : print("Generating quarter cylinder")
Z_Axis = geompy.MakeVectorDXDYDZ(0., 0., 1.)
RotAngle = {'NE' : lambda : 0,
'NW' : lambda : math.pi/2,
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..."
+ 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]])
"""
Output = []
try : Array.index(Element)
- except ValueError : print "No more occurrences"
+ except ValueError : print("No more occurrences")
else : Output.append(Array.index(Element))
if not(Output == []) and len(Array) > 1 :
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)
+ Order = SortList (list(range(NbPts)), Crit)
#print "Sorted Results : ", Order
Output = []
Output.append(Points[Order[0]])
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)
+ Order = SortList(list(range(NbPts)),Cosines)
#print "Ordered points:", Order
for PtIndex in Order[:-1]: Output.append(Points[PtIndex])
determines meshing parameters if necessary and finally launches the generation process.
"""
import Config,GenFunctions
- if Config.debug : print "Initializing object No. " + str(len(Config.ListObj)+1)
+ if Config.debug : print("Initializing object No. " + str(len(Config.ListObj)+1))
if 'publish' in args :
if args['publish']==0 : Config.publish = 0
else : self.GroupNames = [None, None, None, None]
if ObjectType == 'NonOrtho':
- if not(len(GeoParameters)==4): print "Error: trying to construct a non-ortho object but the 4 constitutive vertices are not given!"
+ if not(len(GeoParameters)==4): print("Error: trying to construct a non-ortho object but the 4 constitutive vertices are not given!")
else :
Xmin = min([GeoParameters[i][0] for i in range(4)])
Xmax = max([GeoParameters[i][0] for i in range(4)])
if self.MeshPar[0] < 0 :
Alarms.Message(4)
- if self.MeshPar[0] == -1 : print ("Problem encountered with object(s) no. "+str(ObjectsInvolved))
+ if self.MeshPar[0] == -1 : print(("Problem encountered with object(s) no. "+str(ObjectsInvolved)))
elif self.MeshPar[0] == -2 : print ("This object has no neighbours !!!")
def Boundaries (self):
from itertools import combinations
Boxes = []
if self.Type == 'NonOrtho':
- for combi in combinations(range(4),3):
+ for combi in combinations(list(range(4)),3):
Xmin = min([self.PtCoor[i][0] for i in combi])
Xmax = max([self.PtCoor[i][0] for i in combi])
Ymin = min([self.PtCoor[i][1] for i in combi])
aFilterManager = smesh.CreateFilterManager()
# Building geometric and mesh compounds and groups ##############################################
- if Config.debug : print "Searching for geometric groups and publishing final compound"
+ if Config.debug : print("Searching for geometric groups and publishing final compound")
TempGEOList = []
TempMESHList = []
"""
Output = []
try : Array.index(Element)
- except ValueError : print "No more occurrences"
+ except ValueError : print("No more occurrences")
else : Output.append(Array.index(Element))
if not(Output == [-1]) and len(Array) > 1 :
################################################################################
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."
+ 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."
+ 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."
+ 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'])
################################################################################
if 'Distance' in args : Distance = float(args['Distance'])
else :
- print "\nThe extrusion distance was not given\nA default value of 1 is used."
+ 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."
+ 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'])
# | NW NE | oo
# _____| |_____
-import sys, math, commands
-CWD = commands.getoutput('pwd')
+import sys, math, subprocess
+CWD = subprocess.getoutput('pwd')
sys.path.append(CWD)
from MacObject import *
InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing)))
InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created
if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
- print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience"
+ print("Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience")
DirPar = {'NE' : lambda : ['NE', 'NW', 'SE', 'EW', 'NW', 'SN', 'SN', 'NE', 'WE', 'WE', 'SE', 'NS'],
'NW' : lambda : ['NW', 'NE', 'SW', 'WE', 'NE', 'SN', 'SN', 'NW', 'EW', 'EW', 'SW', 'NS'],
InternalMeshing = int(math.ceil(BoxSide/(3*LocalMeshing)))
InternalMeshing = InternalMeshing+InternalMeshing%2 # An even number is needed, otherwise the objects would not be compatible once created
if InternalMeshing == 0 : InternalMeshing = 2 # This sets a minimum meshing condition in order to avoid an error. The user is notified of the value considered for the local meshing
- print "Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience..."
+ print("Possible Local meshing is :", BoxSide/(3*InternalMeshing), "\nThis value is returned by this function for your convenience...")
DirPar = {'NE' : lambda : ['NE', 'SN', 'NE', 'WE'],
'NW' : lambda : ['NW', 'SN', 'NW', 'EW'],
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())]
import sys
from qtsalome import QSqlQuery
-from tableMaillages import TableMaillages
-from tableMailleurs import TableMailleurs
-from tableMachines import TableMachines
-from tableVersions import TableVersions
-from tableGroupesRef import TableGroupesRef
-from tableGroupes import TableGroupes
-from tableMailles import TableMailles
-from tableTailles import TableTailles
-from tableRatios import TableRatios
-from tableGroupeRatios import TableGroupeRatios
-from tableGroupeTailles import TableGroupeTailles
-from tablePerfs import TablePerfs
+from .tableMaillages import TableMaillages
+from .tableMailleurs import TableMailleurs
+from .tableMachines import TableMachines
+from .tableVersions import TableVersions
+from .tableGroupesRef import TableGroupesRef
+from .tableGroupes import TableGroupes
+from .tableMailles import TableMailles
+from .tableTailles import TableTailles
+from .tableRatios import TableRatios
+from .tableGroupeRatios import TableGroupeRatios
+from .tableGroupeTailles import TableGroupeTailles
+from .tablePerfs import TablePerfs
from Stats.job import Job
from CreeDocuments.jobHtml import Document
self.db.setUserName("");
self.db.setPassword("")
if not self.db.open():
- print(self.db.lastError().text())
+ print((self.db.lastError().text()))
else:
- print "dataBase Open"
+ print("dataBase Open")
self.file=file
def create(self):
bOk,versionId,versionName = self.maTableVersions.chercheVersion(version)
if bOk==False:
self.maTableVersions.creeVersion(version)
- print "nouvelle Version enregistree dans la base"
+ print("nouvelle Version enregistree dans la base")
bOk,versionId,versionName = self.maTableVersions.chercheVersion(version)
if bOk==False:
- print "Impossible de creer la version"
+ print("Impossible de creer la version")
return
bOk,nomMachine = self.maTableMachines.chercheMachine()
if bOk==False:
self.maTableMachines.creeMachine()
- print "enregistrement de la machine dans la table des machines"
+ print("enregistrement de la machine dans la table des machines")
bOk,nomMachine = self.maTableMachines.chercheMachine()
if bOk==False:
- print "Impossible de creer la version"
+ print("Impossible de creer la version")
return
for params in paramMaillage:
- print "___________________________________________"
- print ""
- print " Job : ", params[1]
- print " Version de salome : ", versionName
+ print("___________________________________________")
+ print("")
+ print(" Job : ", params[1])
+ print(" Version de salome : ", versionName)
idJob=params[0]
if mesGroupesRef != [] :
writeFile(fichierGroupesRef,",".join(mesGroupesRef))
monjob=Job(params,salomePath,versionId,mesGroupesRef)
- print ""
- print " Debut d execution"
+ print("")
+ print(" Debut d execution")
monjob.execute()
# remplit Perfs
def compare(self,version,ListeVersionRefString,fichier):
- print "_________________________________________________________________"
- print "Generation du rapport de comparaison"
- print version
+ print("_________________________________________________________________")
+ print("Generation du rapport de comparaison")
+ print(version)
bOk,versionId,versionName = self.maTableVersions.chercheVersion(version)
if bOk==False :
- print "version ", version , " inconnue dans la base"
+ print("version ", version , " inconnue dans la base")
exit()
- print "Version a comparer : ", versionName
+ print("Version a comparer : ", versionName)
versionCompName=versionName
versionCompId=versionId
for id in ListeVersionRef:
bOk,versionId,versionName = self.maTableVersions.chercheVersion(id)
if bOk==False :
- print "version ", id , " inconnue dans la base"
+ print("version ", id , " inconnue dans la base")
exit()
listeVersionRefId.append(versionId)
listeVersionRefName.append(versionName)
maillagesIdListe, maillagesNameListe=self.maTableMaillages.getTous()
if len(maillagesIdListe) != len (listeVersionRefId):
- print "Pas assez de version de reference"
+ print("Pas assez de version de reference")
exit()
allEntitySurMaille=self.maTableMailles.getAllEntity()
# Boucle sur les maillages
for idMaillage in maillagesIdListe :
- print idMaillage
+ print(idMaillage)
versionRefId=listeVersionRefId[idMaillage - 1]
versionRefName=listeVersionRefName[idMaillage - 1]
mailleurId=self.maTableMaillages.getMailleurId(idMaillage)
if os.path.dirname(pathRacine) not in sys.path :
sys.path.insert(0,pathRacine)
-from dataBase import Base
+from .dataBase import Base
if __name__ == "__main__":
from optparse import OptionParser
import sys
import os
-from dataBase import Base
+from .dataBase import Base
p.add_option('-d',dest='database',default="myMesh.db",help='nom de la database')
options, args = p.parse_args()
if len(args) != 1 :
- print "entrer SVP le nom de la directory ou sont rangees les fichiers a charger"
+ print("entrer SVP le nom de la directory ou sont rangees les fichiers a charger")
exit()
folder=args[0]
if not(os.path.isdir(folder)):
- print folder , " n existe pas"
+ print(folder , " n existe pas")
exit()
maBase=Base(options.database)
def insereLigne(self,valeurs,debug=False):
if self.verifieExitenceId(valeurs[0])!=0 :
- print "impossible d inserer " , valeurs, "dans ", self.nom
- print "l id est deja existant"
+ print("impossible d inserer " , valeurs, "dans ", self.nom)
+ print("l id est deja existant")
return False
texteQuery='insert into ' + self.nom + " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery()
- if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
+ if debug : print(texteQuery, " " , maQuery.exec_(texteQuery))
else : maQuery.exec_(texteQuery)
def insereLigneAutoId(self,valeurs,debug=False):
texteQuery='insert into ' + self.nom + self.cols+ " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery()
- if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
+ if debug : print(texteQuery, " " , maQuery.exec_(texteQuery))
else : maQuery.exec_(texteQuery)
def insereOuRemplaceLigne(self,valeurs,debug=False):
texteQuery='insert or replace into ' + self.nom + " values "+ str(valeurs)+ ';'
maQuery=QSqlQuery()
- if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
+ if debug : print(texteQuery, " " , maQuery.exec_(texteQuery))
else : maQuery.exec_(texteQuery)
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
nb=0
- while(maQuery.next()): nb=nb+1
+ while(next(maQuery)): nb=nb+1
return nb
def remplit(self):
- print "Pas de remplissage sauf si cette methode est surchargee"
+ print("Pas de remplissage sauf si cette methode est surchargee")
def createSqlTable(self):
- print "Pas de creation par defaut : cette methode doit etre surchargee"
+ print("Pas de creation par defaut : cette methode doit etre surchargee")
# On ne se sert pas du csv python entre autre parcequ'il ne gere pas les entetes
def exportToCSV(self):
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
asauver=0
- while(maQuery.next()):
+ while(next(maQuery)):
asauver=1
for i in range(len(self.FieldStringList)):
texteSauve+=str(maQuery.value(i).toString())+";"
texteSauve+="\n"
if asauver == 0 :
- print "pas de sauvegarde de : " , self.nom , " table vide"
+ print("pas de sauvegarde de : " , self.nom , " table vide")
return
from Stats.utiles import writeFile
Bok=writeFile(monFichier,texteSauve)
if Bok :
- print "sauvegarde de : " , self.nom , " effectuee "
+ print("sauvegarde de : " , self.nom , " effectuee ")
else :
- print "pas de sauvegarde de : " , self.nom , " IOerror"
+ print("pas de sauvegarde de : " , self.nom , " IOerror")
def importFromCSV(self,folder,force):
monFichier=folder+"/Sauve_"+str(self.nom)+'.csv'
try :
f=open(monFichier,'r')
except:
- print "Pas de chargement de la table ", self.nom
- print "Impossible d'ouvrir le fichier ", monFichier
+ print("Pas de chargement de la table ", self.nom)
+ print("Impossible d'ouvrir le fichier ", monFichier)
return 0
lignes=f.readlines()
enTete=tuple(lignes[0][0:-1].split(";"))
if enTete!=self.FieldStringList:
- print "Pas de chargement de la table ", self.nom
- print "les entetes ne correspondent pas"
+ print("Pas de chargement de la table ", self.nom)
+ print("les entetes ne correspondent pas")
return 0
for StrVal in lignes[1:]:
listeVal=tuple(StrVal[0:-1].split(";"))
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableGroupeRatios (TableDeBase):
def __init__(self):
texteQuery+="foreign key (idVersion) references Versions(id),"
texteQuery+="foreign key (Groupe) references GroupesRef(nomGroupe),"
texteQuery+="primary key (idMaillage,idVersion,Groupe));"
- print "Creation de TableGroupeRatios : " , query.exec_(texteQuery)
+ print("Creation de TableGroupeRatios : " , query.exec_(texteQuery))
def getVal(self,idMaillage, idVersion, Groupe, Entite):
query=QSqlQuery()
query.exec_(texteQuery)
nb=0
val=0 # Valeur si l enregistrement n existe pas
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toFloat()[0]
nb=nb+1
- if nb > 1 : print "Double valeur de Reference dans la table des mailles"
+ if nb > 1 : print("Double valeur de Reference dans la table des mailles")
return val
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableGroupeTailles (TableDeBase):
def __init__(self):
texteQuery+="foreign key (Groupe) references GroupesRef(nomGroupe),"
texteQuery+="primary key (idMaillage,idVersion,Groupe));"
- print "Creation de TableGroupeTailles : " , query.exec_(texteQuery)
+ print("Creation de TableGroupeTailles : " , query.exec_(texteQuery))
def getVal(self,idMaillage, idVersion, Groupe, Entite):
query=QSqlQuery()
query.exec_(texteQuery)
nb=0
val=0 # Valeur si l enregistrement n existe pas
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toFloat()[0]
nb=nb+1
- if nb > 1 : print "Double valeur de Reference dans la table des tailles"
+ if nb > 1 : print("Double valeur de Reference dans la table des tailles")
return val
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableGroupes (TableDeBase):
def __init__(self):
texteQuery+="foreign key (idVersion) references Versions(id),"
texteQuery+="primary key (nomGroupe,idMaillage,idVersion,Entite));"
- print "Creation de TableGroupes : ", query.exec_(texteQuery)
+ print("Creation de TableGroupes : ", query.exec_(texteQuery))
def getVal(self,nomGroupe,idMaillage,idVersion,typeMaille):
texteQuery +=' and idVersion = ' + str(idVersion)
texteQuery +=' and Entite ="' + str(typeMaille) + '";'
query.exec_(texteQuery)
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toInt()[0]
- while (query.next()) :
- print "plusieurs enregistrements dans groupe pour ", nomGroupe," ",str(idMaillage)," ",str(idVersion),"\n"
+ while (next(query)) :
+ print("plusieurs enregistrements dans groupe pour ", nomGroupe," ",str(idMaillage)," ",str(idVersion),"\n")
return val
texteQuery ="select distinct Entite from Groupes;"
query.exec_(texteQuery)
maListe=[]
- while (query.next()) :
+ while (next(query)) :
maListe.append(str(query.value(0).toString()))
return maListe
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableGroupesRef (TableDeBase):
def __init__(self):
texteQuery ="create table GroupesRef(nomGroupe varchar(40), idMaillage int,"
texteQuery+="foreign key (idMaillage) references Maillages(idMaillage),"
texteQuery+="primary key (nomGroupe,idMaillage));"
- print "Creation de TableGroupesRef : " , query.exec_(texteQuery)
+ print("Creation de TableGroupesRef : " , query.exec_(texteQuery))
def getVals(self,idMaillage):
query=QSqlQuery()
texteQuery ='select NomGroupe from GroupesRef where idMaillage='+str(idMaillage) +";"
listeGroupes=[]
query.exec_(texteQuery)
- while (query.next()) :
+ while (next(query)) :
listeGroupes.append(str(query.value(0).toString()))
return listeGroupes
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
import os
class TableMachines (TableDeBase):
def createSqlTable(self):
query=QSqlQuery()
- print "creation de TableMachine : ", query.exec_("create table Machines( nomMachine varchar(10) primary key, os varchar(10));")
+ print("creation de TableMachine : ", query.exec_("create table Machines( nomMachine varchar(10) primary key, os varchar(10));"))
def creeMachine(self):
nomMachine=os.uname()[1]
texteQuery ="select nomMachine from Machines where nomMachine ='" + machine +"' ;"
query.exec_(texteQuery)
nb=0
- while(query.next()):
+ while(next(query)):
nb=nb+1
nom=str(query.value(0).toString())
if nb != 1 : return 0, ""
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableMaillages (TableDeBase):
def __init__(self):
texteQuery+="nomScript varchar(40), medResultat varchar(15), idMailleur int, dimension int,"
texteQuery+="seuilCPU int, seuilRatio int, seuilTaille int, seuilNbMaille int, commentaire varchar(60), "
texteQuery+="foreign key (idMailleur) references Mailleur(id));"
- print "creation de TableMaillages : " , query.exec_(texteQuery)
+ print("creation de TableMaillages : " , query.exec_(texteQuery))
def getVal(self,idMaillage, nomChamp):
query=QSqlQuery()
valeur=None
texteQuery ='select '+ nomChamp + ' from Maillages where id=' + str(idMaillage) + ";"
query.exec_(texteQuery)
- while (query.next()) :
+ while (next(query)) :
valeur=query.value(0).toInt()[0]
- while (query.next()) :
- print "plusieurs enregistrements dans Maillages pour ",str(idMaillage)
+ while (next(query)) :
+ print("plusieurs enregistrements dans Maillages pour ",str(idMaillage))
exit()
return valeur
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
nb=0
- while(maQuery.next()): nb=nb+1
+ while(next(maQuery)): nb=nb+1
return nb
def remplit(self):
if self.dejaRemplie():
- print "table Maillage deja initialisee"
+ print("table Maillage deja initialisee")
return
# self.insereLigneAutoId(('Fiche_7566_TUNNEL', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7566_TUNNEL/Fiche_7566_TUNNEL.py', '/tmp/Fiche_7566_TUNNEL.med', 3,3,10,10,10,10, 'Maillage d un tunnel'))
# self.insereLigneAutoId(('Fiche_7957_AILETTE', '/home/H77945/CAS_TEST/MAILLEUR/FICHE_7957_AILETTE/Fiche_7957_AILETTE.py', '/tmp/Fiche_7957_AILETTE.med', 1,2,10,10,10,10, 'Maillage d une attache d aillette'))
texteQuery="select id, nomScript,medResultat from Maillages;"
maQuery.exec_(texteQuery)
listeMaillages=[]
- while(maQuery.next()):
+ while(next(maQuery)):
listeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString()))
return listeMaillages
texteQuery="select id, nomScript,medResultat from Maillages where id = " + str(idM) +';'
maQuery.exec_(texteQuery)
maSize=0
- while(maQuery.next()):
+ while(next(maQuery)):
maSize+=1
newListeMaillages.append((maQuery.value(0).toInt()[0], maQuery.value(1).toString(), maQuery.value(2).toString()))
if maSize != 1 :
- print "impossible de traiter le maillage : ", idM
+ print("impossible de traiter le maillage : ", idM)
return newListeMaillages
def getSeuilsPourMaillage(self,idMaillage):
texteQuery="select id,nomMaillage,seuilCPU,seuilRatio,seuilTaille,seuilNbMaille from Maillages where id = "+ str(idMaillage) +" ;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
- while(maQuery.next()):
+ while(next(maQuery)):
l1 = maQuery.value(0).toInt()[0]
l2 = maQuery.value(1).toString()
l3 = maQuery.value(2).toInt()[0]
texteQuery="select id,nomMaillage from Maillages order by id;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
- while(maQuery.next()):
+ while(next(maQuery)):
maillagesIdListe.append( maQuery.value(0).toInt()[0])
maillagesNomListe.append( maQuery.value(1).toString())
return maillagesIdListe, maillagesNomListe
def getMailleurId(self,idMaillage):
texteQuery="select idMailleur from Maillages where id = "+ str(idMaillage) +" ;"
maQuery=QSqlQuery()
- print texteQuery
- print maQuery.exec_(texteQuery)
+ print(texteQuery)
+ print(maQuery.exec_(texteQuery))
maQuery.exec_(texteQuery)
- while(maQuery.next()):
+ while(next(maQuery)):
idMailleur = maQuery.value(0).toInt()[0]
return idMailleur
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableMailles (TableDeBase):
def __init__(self):
texteQuery+="foreign key (idVersion) references Versions(id),"
texteQuery+="primary key (idMaillage,idVersion,Entite));"
- print "Creation de TableMailles : " , query.exec_(texteQuery)
+ print("Creation de TableMailles : " , query.exec_(texteQuery))
def getVal(self,idMaillage, idVersion, Entite):
query.exec_(texteQuery)
nb=0
val=0 # Valeur si l enregistrement n existe pas
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toInt()[0]
nb=nb+1
- if nb > 1 : print "Double valeur de Reference dans la table des mailles"
+ if nb > 1 : print("Double valeur de Reference dans la table des mailles")
return val
texteQuery ="select distinct Entite from Mailles;"
query.exec_(texteQuery)
maListe=[]
- while (query.next()) :
+ while (next(query)) :
maListe.append(str(query.value(0).toString()))
return maListe
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableMailleurs (TableDeBase):
def __init__(self):
def createSqlTable(self):
query=QSqlQuery()
- print "Creation de TableMailleurs", query.exec_("create table Mailleurs(id integer primary key autoincrement, nomMailleur varchar(40));")
+ print("Creation de TableMailleurs", query.exec_("create table Mailleurs(id integer primary key autoincrement, nomMailleur varchar(40));"))
def dejaRemplie(self):
texteQuery="select * from Mailleurs where nomMailleur='Blsurf+Ghs3D';"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
nb=0
- while(maQuery.next()): nb=nb+1
+ while(next(maQuery)): nb=nb+1
return nb
def remplit(self):
if self.dejaRemplie() :
- print "Table Mailleurs deja initialisee"
+ print("Table Mailleurs deja initialisee")
return
self.insereLigneAutoId(('BLSURF',))
self.insereLigneAutoId(('NETGEN1D2D',))
# difficulte a construire le texte avec une seule valeur
texteQuery='insert into Mailleurs (nomMailleur) values ("'+ str(valeurs[0])+ '");'
maQuery=QSqlQuery()
- if debug : print texteQuery, " " , maQuery.exec_(texteQuery)
+ if debug : print(texteQuery, " " , maQuery.exec_(texteQuery))
else : maQuery.exec_(texteQuery)
def getTous(self):
texteQuery="select * from Mailleurs;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
- while(maQuery.next()):
+ while(next(maQuery)):
l1.append( maQuery.value(0).toInt()[0])
l2.append( maQuery.value(1).toString())
return l1,l2
texteQuery="select nomMailleur from Mailleurs where id = " + str(mailleurId) + " ;"
maQuery=QSqlQuery()
maQuery.exec_(texteQuery)
- while(maQuery.next()):
+ while(next(maQuery)):
mailleurName=maQuery.value(0).toString()
return mailleurName
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TablePerfs (TableDeBase):
def __init__(self):
texteQuery+="foreign key (Machine) references Machines(nomMachine),"
texteQuery+="primary key (idMaillage, idVersion, Machine));"
- print "Creation de TablePerfs : " , query.exec_(texteQuery)
+ print("Creation de TablePerfs : " , query.exec_(texteQuery))
def getVal(self,idMaillage,idVersion,Machine):
query=QSqlQuery()
texteQuery +=" and Machine ='" + Machine + "';"
query.exec_(texteQuery)
cpu=None
- while (query.next()) :
+ while (next(query)) :
cpu=query.value(0).toInt()[0]
- while (query.next()) :
- print "plusieurs enregistrements dans perf pour ",str(idMaillage)," ",str(idVersion)," ",Machine
+ while (next(query)) :
+ print("plusieurs enregistrements dans perf pour ",str(idMaillage)," ",str(idVersion)," ",Machine)
if cpu==None :
- print "pas d enregistrement dans perf pour ",str(idMaillage)," ",str(idVersion)," ",Machine
+ print("pas d enregistrement dans perf pour ",str(idMaillage)," ",str(idVersion)," ",Machine)
return cpu
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableRatios (TableDeBase):
def __init__(self):
texteQuery+="foreign key (idVersion) references Versions(id),"
texteQuery+="primary key (idMaillage,idVersion));"
- print "Creation de TableRatios : " , query.exec_(texteQuery)
+ print("Creation de TableRatios : " , query.exec_(texteQuery))
def getVal(self,idMaillage, idVersion, Entite):
query=QSqlQuery()
query.exec_(texteQuery)
nb=0
val=0 # Valeur si l enregistrement n existe pas
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toFloat()[0]
nb=nb+1
- if nb > 1 : print "Double valeur de Reference dans la table des mailles"
+ if nb > 1 : print("Double valeur de Reference dans la table des mailles")
return val
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableTailles (TableDeBase):
def __init__(self):
texteQuery+="foreign key (idVersion) references Versions(id),"
texteQuery+="primary key (idMaillage,idVersion));"
- print "Creation de TableTailles : " , query.exec_(texteQuery)
+ print("Creation de TableTailles : " , query.exec_(texteQuery))
def getVal(self,idMaillage, idVersion, Entite):
query=QSqlQuery()
query.exec_(texteQuery)
nb=0
val=0 # Valeur si l enregistrement n existe pas
- while (query.next()) :
+ while (next(query)) :
val=query.value(0).toFloat()[0]
nb=nb+1
- if nb > 1 : print "Double valeur de Reference dans la table des mailles"
+ if nb > 1 : print("Double valeur de Reference dans la table des mailles")
return val
from qtsalome import QSqlQuery
-from tableDeBase import TableDeBase
+from .tableDeBase import TableDeBase
class TableVersions (TableDeBase):
def __init__(self):
query=QSqlQuery()
texteQuery ="create table Versions(id integer primary key autoincrement, nomVersion varchar(10),"
texteQuery+="commentaire varchar(30));"
- print "Creation de TableVersions : " , query.exec_(texteQuery)
+ print("Creation de TableVersions : " , query.exec_(texteQuery))
def remplit(self):
texteQuery ="select id, nomVersion from Versions where nomVersion ='" + version +"' ;"
query.exec_(texteQuery)
nb=0
- while(query.next()):
+ while(next(query)):
nb=nb+1
id=query.value(0).toInt()[0]
nom=query.value(1).toString()
if __name__ == "__main__":
- print Chercheversion("/local00/home/A96028/Appli")
+ print(Chercheversion("/local00/home/A96028/Appli"))
start = trouve + len(subString)
def FormateTexte(texte,dico):
- for clef in dico.keys():
+ for clef in list(dico.keys()):
texteARemplacer="%"+str(clef)+"%"
remplacement=dico[clef]
if texte.find(texteARemplacer) < 0 :
- print "impossible de remplacer ",texteARemplacer, "Pas d'occurence"
- print remplacement
+ print("impossible de remplacer ",texteARemplacer, "Pas d'occurence")
+ print(remplacement)
continue
if compte_all(texte,texteARemplacer) != 1 :
- print "impossible de remplacer ",texteARemplacer, "trop d'occurences"
+ print("impossible de remplacer ",texteARemplacer, "trop d'occurences")
continue
remplacement=str(remplacement)
texte=texte.replace(texteARemplacer,remplacement)
from desFenetreChoix_ui import Ui_Choix
from qtsalome import *
-from monEditor import TableEditor
+from .monEditor import TableEditor
# Import des panels
self.view.pressed.connect(self.donneLigne)
def donneLigne(self):
- print "jjjjjjjjjjjjjjjj"
+ print("jjjjjjjjjjjjjjjj")
def setTitle(self):
fields=self.table.getFields()
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):
import SMESH
for i in range(len(mesures)):
txt += str(SMESH.EntityType._item(i))+ " " +str(mesures[SMESH.EntityType._item(i)]) + "\n"
- from utiles import writeFile
+ from .utiles import writeFile
writeFile(fichier,txt)
fichierGroupe=fichierMedResult.replace('.med','_groupesRef.res')
lGroups=getGroupesRef(fichierGroupe)
if len(lGroups)==0:
- print "pas de Groupe de Reference "
+ print("pas de Groupe de Reference ")
try :
os.remove(fichierGroupe)
return
import SMESH
for i in range(len(mesures)):
txt += str(SMESH.EntityType._item(i))+ " " +str(mesures[SMESH.EntityType._item(i)]) + "\n"
- from utiles import writeFile
+ from .utiles import writeFile
writeFile(fichierStatGroupe,txt)
a=os.system(commande+" -t "+script)
fin=time.time()
self.CPU=fin-debut
- print " Temps d execution : ", self.CPU
+ print(" Temps d execution : ", self.CPU)
#stdout, stderr = p.communicate()
try:
text=open(self.fichierStatResult).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(self.fichierStatResult)
+ print("Impossible d'ouvrir le fichier: ", str(self.fichierStatResult))
exit(1)
liste=text.split()
i=0
try:
text=open(fichier).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(fichier)
+ print("Impossible d'ouvrir le fichier: ", str(fichier))
exit(1)
liste=text.split(",")
return liste
try:
text=open(fichier).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(fichier)
+ print("Impossible d'ouvrir le fichier: ", str(fichier))
exit(1)
liste=text.split(",")
return liste
try:
text=open(fichier).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(fichier)
+ print("Impossible d'ouvrir le fichier: ", str(fichier))
exit(1)
liste=text.split()
i=0
try:
text=open(fichier).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(fichier)
+ print("Impossible d'ouvrir le fichier: ", str(fichier))
exit(1)
liste=text.split(",")
# print "taille",liste
try:
text=open(fichier).read()
except:
- print "Impossible d'ouvrir le fichier: ", str(fichier)
+ print("Impossible d'ouvrir le fichier: ", str(fichier))
exit(1)
liste=text.split(",")
return liste
seuil=self.maBase.maTableMaillages.getVal(self.idMaillage,"seuilCPU")
seuilHaut=cpuAvant*(100+seuil)/100.
if NbSec > seuilHaut :
- print "Probleme consommation CPU : "
- print " cpu reference : ", cpuAvant
- print " seuil : ", seuil
- print " CPU : ", NbSec
+ print("Probleme consommation CPU : ")
+ print(" cpu reference : ", cpuAvant)
+ print(" seuil : ", seuil)
+ print(" CPU : ", NbSec)
return True
return False
seuilHaut=valAvant*(100+seuil)/100.
seuilBas=valAvant*(100-seuil)/100.
if (valTrouvee < seuilBas) or (valTrouvee > seuilHaut) :
- print "Probleme sur le nombre de Mailles de type : ", nomColonne
- print " nb reference : ", valAvant
- print " seuil : ", seuil
- print " nb : ", valTrouvee
+ print("Probleme sur le nombre de Mailles de type : ", nomColonne)
+ print(" nb reference : ", valAvant)
+ print(" seuil : ", seuil)
+ print(" nb : ", valTrouvee)
return True
i=i+1
return False
seuilHaut=valAvant*(100+seuil)/100.
seuilBas=valAvant*(100-seuil)/100.
if (valTrouvee < seuilBas) or (valTrouvee > seuilHaut) :
- print "Probleme sur le nombre de Mailles de type : ", nomColonne
- print " nb reference : ", valAvant
- print " seuil : ", seuil
- print " nb : ", valTrouvee
+ print("Probleme sur le nombre de Mailles de type : ", nomColonne)
+ print(" nb reference : ", valAvant)
+ print(" seuil : ", seuil)
+ print(" nb : ", valTrouvee)
return True
i=i+1
return False
seuilHaut=valAvant*(100+seuil)/100.
seuilBas=valAvant*(100-seuil)/100.
if (valTrouvee < seuilBas) or (valTrouvee > seuilHaut) :
- print "Probleme sur le nombre de Mailles de type : ", nomColonne
- print " nb reference : ", valAvant
- print " seuil : ", seuil
- print " nb : ", valTrouvee
+ print("Probleme sur le nombre de Mailles de type : ", nomColonne)
+ print(" nb reference : ", valAvant)
+ print(" seuil : ", seuil)
+ print(" nb : ", valTrouvee)
return True
return False
seuilHaut=valAvant*(100+seuil)/100
seuilBas=valAvant*(100-seuil)/100
if (valTrouvee < seuilBas) or (valTrouvee > seuilHaut) :
- print "Probleme sur le nombre de Mailles de type : ", nomColonne, "pour le groupe ", nomGroupe
- print " nb reference : ", valAvant
- print " seuil : ", seuil
- print " nb : ", valTrouvee
+ print("Probleme sur le nombre de Mailles de type : ", nomColonne, "pour le groupe ", nomGroupe)
+ print(" nb reference : ", valAvant)
+ print(" seuil : ", seuil)
+ print(" nb : ", valTrouvee)
return True
return False
if txt == None : return
if fn == None : return
- fn = unicode(fn)
+ fn = str(fn)
try:
f = open(fn, 'wb')
f.write(txt)
sys.path.insert(0,installDir)
from qtsalome import *
-from Base.dataBase import Base
+from .Base.dataBase import Base
def completeDatabase(fichier,table,enregistrement):
maBase=Base(fichier)
nbCols=model.columnCount() -1
if table == "TableGroupesRef" : nbCols==nbCols+1
if len(enregistrement) != nbCols :
- print "mauvais nb de valeurs"
- print "Attention, ne pas renter d'Id"
+ print("mauvais nb de valeurs")
+ print("Attention, ne pas renter d'Id")
if table == "TableGroupesRef" : matable.insereLigne(enregistrement)
else : matable.insereLigneAutoId(enregistrement)
maBase.close()
p.add_option('-t',dest='table',help='nom de la table a completer')
options, args = p.parse_args()
if options.table==None :
- print "table obligatoire"
+ print("table obligatoire")
exit()
if options.table not in ("TableMaillages","TableMailleurs","TableGroupesRef","TableVersions") :
- print "la table doit etre : TableMaillages ou TableMailleurs ou TableGroupesRef ou TableVersions"
+ print("la table doit etre : TableMaillages ou TableMailleurs ou TableGroupesRef ou TableVersions")
exit()
enregistrement=tuple(args)
completeDatabase(options.database,options.table,enregistrement)
import sys
import os
-from Base.dataBase import Base
-from Base.versions import Chercheversion
+from .Base.dataBase import Base
+from .Base.versions import Chercheversion
if __name__ == "__main__":
#!/usr/bin/env python
import sys
-from Base.dataBase import Base
+from .Base.dataBase import Base
def creeDatabase(fichier):
maBase=Base(fichier)
#!/usr/bin/env python
from qtsalome import *
-from Gui.myMain_ui import Ui_Gestion
+from .Gui.myMain_ui import Ui_Gestion
import sys
pass
def BCreePressed(self):
- from Gui.monNomBase import DataBaseName
+ from .Gui.monNomBase import DataBaseName
maW=DataBaseName(self)
maW.exec_()
- from createDatabase import creeDatabase
+ from .createDatabase import creeDatabase
creeDatabase(self.nomBase)
def BVuePressed(self):
if self.nomBase == "" :
- from Gui.monNomBase import DataBaseName
+ from .Gui.monNomBase import DataBaseName
maW=DataBaseName(self)
maW.exec_()
- from Gui.maFenetreChoix import MaFenetreChoix
- from Base.dataBase import Base
+ from .Gui.maFenetreChoix import MaFenetreChoix
+ from .Base.dataBase import Base
maBase=Base(self.nomBase)
maBase.initialise()
window = MaFenetreChoix(maBase)
import sys
import os
-from Base.dataBase import Base
-from Base.versions import Chercheversion
+from .Base.dataBase import Base
+from .Base.versions import Chercheversion
if __name__ == "__main__":
p.add_option('-f',dest='force',default=True,help='force la passage des jobs meme si l execution a deja eu lieu sur cette machine pour cette version de salome')
options, args = p.parse_args()
if len(args) == 0 and options.all== False:
- print "Enter -a ou un numero de job"
- print 2
+ print("Enter -a ou un numero de job")
+ print(2)
exit()
if options.salomePath==None :
- print "chemin du runAppli obligatoire"
+ print("chemin du runAppli obligatoire")
exit()
if options.version==None :
options.version=Chercheversion(options.salomePath)
f.write(cmds)
self.make_executable(nomFichier)
- if verbose: print("INFO: MGSurfOpt launch script file: %s" % nomFichier)
+ if verbose: print(("INFO: MGSurfOpt launch script file: %s" % nomFichier))
self.monExe.start(nomFichier)
self.monExe.closeWriteChannel()
savedir=os.environ['HOME']
fn = QFileDialog.getSaveFileName(None,"Save File",savedir)
if fn.isNull() : return
- ulfile = os.path.abspath(unicode(fn))
+ ulfile = os.path.abspath(str(fn))
try:
f = open(fn, 'wb')
f.write(str(self.TB_Exe.toPlainText()))
f.close()
- except IOError, why:
+ except IOError as why:
QMessageBox.critical(self, 'Save File',
- 'The file <b>%1</b> could not be saved.<br>Reason: %2'%(unicode(fn), str(why)))
+ 'The file <b>%1</b> could not be saved.<br>Reason: %2'%(str(fn), str(why)))
def readFromStdErr(self):
a=self.monExe.readAllStandardError()
- self.TB_Exe.append(unicode(a.data().encode()))
+ self.TB_Exe.append(str(a.data().encode()))
def readFromStdOut(self) :
a=self.monExe.readAllStandardOutput()
- aa=unicode(a.data())
+ aa=str(a.data())
self.TB_Exe.append(aa)
def finished(self):
#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)
if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
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):
if salome.sg.hasDesktop(): salome.sg.updateObjBrowser(False)
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())
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 os, tempfile, shutil
-import utilityFunctions as uF
-from output import message
+from . import utilityFunctions as uF
+from .output import message
def medToGeo(medFile, geoFile, tmpdir, opt=[], verbose=0):
medLoc=os.path.dirname(medFile)
maxS=data['maxSize'][0]
extrL=data['extractLength'][0]
- grad = data['gradation'][0] if 'gradation' in data.keys() else 1.3
- quad = data['quad'] if 'quad' in data.keys() else False
- cas2D = data['is2D'] if 'is2D' in data.keys() else False
- refine = data['refine'] if 'refine' in data.keys() else False
- nbLay = data['layers'][0] if 'layers' in data.keys() else 5
- nbIter = data['iterations'][0] if 'iterations' in data.keys() else 2
-
- Gvol = data['grVol'] if 'grVol' in data.keys() else ''
- Gfac = data['grFace'] if 'grFace' in data.keys() else ''
- Gedg = data['grEdge'] if 'grEdge' in data.keys() else ''
- Gnod = data['grNodes'] if 'grNodes' in data.keys() else ''
- surfOpt = data['surfopt'] if 'surfopt' in data.keys() else ''
+ grad = data['gradation'][0] if 'gradation' in list(data.keys()) else 1.3
+ quad = data['quad'] if 'quad' in list(data.keys()) else False
+ cas2D = data['is2D'] if 'is2D' in list(data.keys()) else False
+ refine = data['refine'] if 'refine' in list(data.keys()) else False
+ nbLay = data['layers'][0] if 'layers' in list(data.keys()) else 5
+ nbIter = data['iterations'][0] if 'iterations' in list(data.keys()) else 2
+
+ Gvol = data['grVol'] if 'grVol' in list(data.keys()) else ''
+ Gfac = data['grFace'] if 'grFace' in list(data.keys()) else ''
+ Gedg = data['grEdge'] if 'grEdge' in list(data.keys()) else ''
+ Gnod = data['grNodes'] if 'grNodes' in list(data.keys()) else ''
+ surfOpt = data['surfopt'] if 'surfopt' in list(data.keys()) else ''
if not os.path.isdir(tmpdir): os.mkdir(tmpdir)
import sys, os, shutil, pickle, tempfile
-import main, genereCrack, Zset
-import utilityFunctions as uF
+from . import main, genereCrack, Zset
+from . import utilityFunctions as uF
#commande="/bin/bash -c ""source $HOME/zebulon/Z8.6.6_NEW/do_config_bash"""
#os.system(commande)
def SCRIPT(dataFile=None, data=None, dim=3, names=None):
if dim!=3 and dim!=2:
- print 'ERROR'
+ print('ERROR')
return(False)
if dataFile==None and data==None:
- print 'One of dataFile or data is mandatory'
+ print('One of dataFile or data is mandatory')
return(False)
if data==None: data=pickle.load(open(dataFile,'r'))
- print data
+ print(data)
tmpdir=tempfile.mkdtemp()
uF.removeFromSessionPath('LD_LIBRARY_PATH', 'Meshgems-2111')
for f in [crackMed, crackedMed, saneGeo, crackGeo, crackedGeo]:
if os.path.isfile(f): os.remove(f)
- print crackMed
+ print(crackMed)
genereCrack.main(data, crackMed)
goOn=os.path.isfile(crackMed)
from Zcracks import genereCrack, Zset
from Zcracks import utilityFunctions as uF
-import genereCube
+from . import genereCube
from math import sqrt
#tmpdir = "/local00/home/B27118/projets/Zcracks/Zcracks/casTests/tmpdir"
#if not os.path.isdir(tmpdir): os.mkdir(tmpdir)
tmpdir=tempfile.mktemp(prefix='tmpZcracks')
-print "tmpdir=", tmpdir
+print("tmpdir=", tmpdir)
meshgemsdir=os.environ('MESHGEMSHOME')
if len(meshgemsdir) > 0:
OK=[]
NOOK=[]
- for s in synthese.keys():
+ for s in list(synthese.keys()):
if synthese[s]:
OK.append(s)
else:
NOOK.append(s)
- print 'OK:'
- print OK
- print ' '
- print 'NOOK:'
- print NOOK
- print ' '
+ print('OK:')
+ print(OK)
+ print(' ')
+ print('NOOK:')
+ print(NOOK)
+ print(' ')
return(synthese)
import os, tempfile
directory=tempfile.mktemp(prefix='tmpZcracks')
-print "directory=", tmpdir
+print("directory=", tmpdir)
# Tous les cas
listCas=['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']
synthese[cas]= os.path.isfile(result)
-print synthese
+print(synthese)
from salome.geom import geomBuilder
import math
import SALOMEDS
-import utilityFunctions as uF
-from output import message
+from . import utilityFunctions as uF
+from .output import message
#ellipse.generate(data_demi_grand_axe, data_centre, data_normale,data_direction, data_demi_petit_axe, data_angle, rayon_entaille,extension, outFile)
#if True:
Maillage.ExportMED( outFile, 0, SMESH.MED_V2_2, 1, None ,1)
smesh.SetName(Maillage.GetMesh(), 'MAILLAGE_FISSURE')
except:
- print 'ExportToMEDX() failed. Invalid file name?'
+ print('ExportToMEDX() failed. Invalid file name?')
## Set names of Mesh objects
import os, shutil
-import sphere, ellipse, rectangle
-import utilityFunctions as uF
-from output import message
+from . import sphere, ellipse, rectangle
+from . import utilityFunctions as uF
+from .output import message
def main(data, outFile):
activeCrack=data['crack']['actif']
res=False
demiGrandAxe=crack['Rayon'][0]
- if 'Rayon 2' not in crack.keys(): crack['Rayon 2']=[]
+ if 'Rayon 2' not in list(crack.keys()): crack['Rayon 2']=[]
if len(crack['Rayon 2'])==0:
demiPetitAxe=demiGrandAxe
else:
res=False
normale=crack['Normale']
- if 'Direction' not in crack.keys(): crack['Direction']=[]
+ if 'Direction' not in list(crack.keys()): crack['Direction']=[]
if len(crack['Direction'])==0:
if normale==[1.,0.,0.]:
direction=[0.,1.,0.]
message('E','Normale and Direction are equals',goOn=True)
res=False
- if 'Angle' not in crack.keys(): crack['Angle']=[]
+ if 'Angle' not in list(crack.keys()): crack['Angle']=[]
if len(crack['Angle'])==0:
angle=0.0
else:
res=False
angle=crack['Angle'][0]
- if 'Rayon entaille' not in crack.keys(): crack['Rayon entaille']=[]
+ if 'Rayon entaille' not in list(crack.keys()): crack['Rayon entaille']=[]
if len(crack['Rayon entaille'])==0:
rayon_entaille=0.0
else:
res=False
rayon_entaille=crack['Rayon entaille'][0]
- if 'Extension' not in crack.keys(): crack['Extension']=[]
+ if 'Extension' not in list(crack.keys()): crack['Extension']=[]
if len(crack['Extension'])==0:
extension=0.0
else:
res=False
longueur=crack['Longueur'][0]
- if 'Largeur' not in crack.keys(): crack['Largeur']=[]
+ if 'Largeur' not in list(crack.keys()): crack['Largeur']=[]
if len(crack['Largeur'])==0:
largeur=longueur
else:
res=False
direction=crack['Direction']
- if 'Angle' not in crack.keys(): crack['Angle']=[]
+ if 'Angle' not in list(crack.keys()): crack['Angle']=[]
if len(crack['Angle'])==0:
angle=0.0
else:
res=False
angle=crack['Angle'][0]
- if 'Rayon' not in crack.keys(): crack['Rayon']=[]
+ if 'Rayon' not in list(crack.keys()): crack['Rayon']=[]
if len(crack['Rayon'])==0:
rayon=0.0
else:
res=False
rayon=crack['Rayon'][0]
- if 'Rayon entaille' not in crack.keys(): crack['Rayon entaille']=[]
+ if 'Rayon entaille' not in list(crack.keys()): crack['Rayon entaille']=[]
if len(crack['Rayon entaille'])==0:
rayon_entaille=0.0
else:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
-import utilityFunctions as uF
-import genereCrack, Zset, output, zcracks_ui
+from . import utilityFunctions as uF
+from . import genereCrack, Zset, output, zcracks_ui
-from output import message, init
-from zcracks_ui import Ui_Zui
+from .output import message, init
+from .zcracks_ui import Ui_Zui
# ---------------------
if str(string).replace(' ','')=='':
out=[]
else:
- out=map(typ, str(string).split())
+ out=list(map(typ, str(string).split()))
return(out)
def addExtension(string, extension):
else:
obj.setText(QString(self.data[self.lineEditNames[cont]]))
- self.ui.CBQuad.setChecked(True if 'quad' in self.data.keys() and self.data['quad'] else False)
- self.ui.CBBarsoum.setChecked(True if 'barsoum' in self.data.keys() and self.data['barsoum'] else False)
- self.ui.CBIs2D.setChecked(True if 'is2D' in self.data.keys() and self.data['is2D'] else False)
- self.ui.CBRefine.setChecked(True if 'refine' in self.data.keys() and self.data['refine'] else False)
+ self.ui.CBQuad.setChecked(True if 'quad' in list(self.data.keys()) and self.data['quad'] else False)
+ self.ui.CBBarsoum.setChecked(True if 'barsoum' in list(self.data.keys()) and self.data['barsoum'] else False)
+ self.ui.CBIs2D.setChecked(True if 'is2D' in list(self.data.keys()) and self.data['is2D'] else False)
+ self.ui.CBRefine.setChecked(True if 'refine' in list(self.data.keys()) and self.data['refine'] else False)
if not test2:
message('A','No mesh file to visualize')
else:
- print medit+' %s' %meshFile2
+ print(medit+' %s' %meshFile2)
system(medit+' %s' %meshFile2)
else:
- print medit+' %s' %meshFile1
+ print(medit+' %s' %meshFile1)
system(medit+' %s' %meshFile1)
return()
from salome.geom import geomBuilder
import math
import SALOMEDS
-import utilityFunctions as uF
-from output import message
+from . import utilityFunctions as uF
+from .output import message
#import GEOM_Gen.ild
#rectangle.generate(data_longueur,data_largeur,data_centre,data_normale,data_direction,data_angle,data_rayon,rayon_entaille,extension,outFile)
Maillage.ExportMED( outFile, 0, SMESH.MED_V2_2, 1, None ,1)
smesh.SetName(Maillage.GetMesh(), 'MAILLAGE_FISSURE')
except:
- print 'ExportToMEDX() failed. Invalid file name?'
+ print('ExportToMEDX() failed. Invalid file name?')
if salome.sg.hasDesktop():
from salome.geom import geomBuilder
import math
import SALOMEDS
-import utilityFunctions as uF
-from output import message
+from . import utilityFunctions as uF
+from .output import message
#import GEOM_Gen.ild
Maillage.ExportMED( outFile, 0, SMESH.MED_V2_2, 1, None ,1)
smesh.SetName(Maillage.GetMesh(), 'MAILLAGE_FISSURE')
except:
- print 'ExportToMEDX() failed. Invalid file name?'
+ print('ExportToMEDX() failed. Invalid file name?')
## Set names of Mesh objects
import numpy, subprocess, sys
from os import remove, getpid, path, environ
-from output import message
+from .output import message
def calcCoordVectors(normalIN, directionIN):
V3TEMP=numpy.cross(normalIN,directionIN)
while ifChanged :
ifChanged=False
for elemId in elemList[0]:
- minColor=sys.maxint
- maxColor=-sys.maxint
+ minColor=sys.maxsize
+ maxColor=-sys.maxsize
for elemNodeId in mesh.GetElemNodes(elemId) :
nodeColor=colorList[elemNodeId-1]
if nodeColor<minColor : minColor=nodeColor
def getMaxAspectRatio(tmpdir):
logFile=path.join(tmpdir,'MESHING_OUTPUT')
- print logFile
+ print(logFile)
if not path.isfile(logFile): return(-1)
import re
if command is not "":
try:
subprocess.check_call(command, executable = '/bin/bash', shell = True, bufsize=-1)
- except Exception, e:
- print "Error: ",e
+ except Exception as e:
+ print("Error: ",e)
self.valIterations.setToolTip(_translate("Zui", "integer (ex: 2)", None))
self.valIterations.setText(_translate("Zui", "2", None))
-import images_rc
+from . import images_rc
# -*- coding: utf-8 -*-
-from cubeAngle import cubeAngle
+from .cubeAngle import cubeAngle
class cubeAngle2(cubeAngle):
"""
import SMESH
import logging
-from cylindre import cylindre
+from .cylindre import cylindre
from blocFissure.gmu.triedreBase import triedreBase
from blocFissure.gmu.genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
#import NETGENPlugin
import logging
-from ellipse_1 import ellipse_1
+from .ellipse_1 import ellipse_1
from blocFissure.gmu.triedreBase import triedreBase
from blocFissure.gmu.genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
#import NETGENPlugin
import logging
-from eprouvetteDroite import eprouvetteDroite
+from .eprouvetteDroite import eprouvetteDroite
from blocFissure.gmu.triedreBase import triedreBase
from blocFissure.gmu.genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
problemes[i].executeProbleme()
except:
traceback.print_exc()
- print "---------------------------------------------------------------------"
+ print("---------------------------------------------------------------------")
# -*- coding: utf-8 -*-
-from fissure_Coude import fissure_Coude
+from .fissure_Coude import fissure_Coude
class fissure_Coude_4(fissure_Coude):
"""
orientation : 0° : longitudinale, 90° : circonférentielle, autre : uniquement fissures elliptiques
externe : True : fissure face externe, False : fissure face interne
"""
- print "setParamShapeFissure", self.nomCas
+ print("setParamShapeFissure", self.nomCas)
self.shapeFissureParams = dict(nomRep = '.',
nomFicSain = self.nomCas,
nomFicFissure = 'fissure_' + self.nomCas,
# -*- coding: utf-8 -*-
import os
-import initLog
+from . import initLog
# --- calcul path blocFissure
import logging
-from geomsmesh import geompy
-from findWireIntermediateVertices import findWireIntermediateVertices
-from projettePointSurCourbe import projettePointSurCourbe
+from .geomsmesh import geompy
+from .findWireIntermediateVertices import findWireIntermediateVertices
+from .projettePointSurCourbe import projettePointSurCourbe
def ajustePointsEdgePipeFissure(edgesPipeFissureExterneC, wirePipeFissureExterne, gptsdisks, idisklim):
"""
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- bloc defaut
import logging
import math
-from geomsmesh import geompy
-from geomsmesh import smesh
+from .geomsmesh import geompy
+from .geomsmesh import smesh
def calculePointsAxiauxPipe(edgesFondFiss, edgesIdByOrientation, facesDefaut,
centreFondFiss, wireFondFiss, wirePipeFiss,
# -*- coding: utf-8 -*-
import os
-from geomsmesh import geompy, smesh
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
+from .geomsmesh import geompy, smesh
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
import math
import GEOM
#import NETGENPlugin
import logging
-from fissureGenerique import fissureGenerique
+from .fissureGenerique import fissureGenerique
-from initEtude import initEtude
-from triedreBase import triedreBase
-from genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
-from creeZoneDefautDansObjetSain import creeZoneDefautDansObjetSain
-from construitFissureGenerale import construitFissureGenerale
+from .initEtude import initEtude
+from .triedreBase import triedreBase
+from .genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
+from .creeZoneDefautDansObjetSain import creeZoneDefautDansObjetSain
+from .construitFissureGenerale import construitFissureGenerale
O, OX, OY, OZ = triedreBase()
initEtude()
self.references = references
self.dicoParams = dicoParams
- if self.dicoParams.has_key('nomCas'):
+ if 'nomCas' in self.dicoParams:
self.nomCas = self.dicoParams['nomCas']
- elif self.dicoParams.has_key('nomres'):
+ elif 'nomres' in self.dicoParams:
self.nomCas = os.path.splitext(os.path.split(self.dicoParams['nomres'])[1])[0]
else:
self.nomCas = 'casStandard'
- if self.dicoParams.has_key('reptrav'):
+ if 'reptrav' in self.dicoParams:
self.reptrav = self.dicoParams['reptrav']
else:
self.reptrav = '.'
self.nomCas = self.nomProbleme +"_%d"%(self.numeroCas)
else:
self.nomProbleme = self.nomCas
- if self.dicoParams.has_key('lenSegPipe'):
+ if 'lenSegPipe' in self.dicoParams:
self.lenSegPipe = self.dicoParams['lenSegPipe']
else:
self.lenSegPipe =self.dicoParams['rayonPipe']
- if self.dicoParams.has_key('step'):
+ if 'step' in self.dicoParams:
step = self.dicoParams['step']
else:
step = -1 # exécuter toutes les étapes
- if not self.dicoParams.has_key('aretesVives'):
+ if 'aretesVives' not in self.dicoParams:
self.dicoParams['aretesVives'] = 0
if self.numeroCas == 0: # valeur par défaut : exécution immédiate, sinon execution différée dans le cas d'une liste de problèmes
self.executeProbleme(step)
pointIn_x : optionnel : coordonnée x d'un point dans le solide sain (pour orienter la face - idem avec y,z)
"""
logging.info("setParamShapeFissure %s", self.nomCas)
- if self.dicoParams.has_key('pointInterieur'):
+ if 'pointInterieur' in self.dicoParams:
self.shapeFissureParams = dict(lgInfluence = self.dicoParams['lgInfluence'],
rayonPipe = self.dicoParams['rayonPipe'],
lenSegPipe = self.lenSegPipe,
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- teste si l'opération de partition a produit une modification
info = geompy.ShapeInfo(shape)
logging.debug("shape info %s", info)
for k in ['VERTEX', 'EDGE', 'FACE', 'SOLID']:
- if k in orig.keys():
+ if k in list(orig.keys()):
orig[k] += info[k]
else:
orig[k] = info[k]
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- subShapes communes à deux listes
idsub1[geompy.GetSubShapeID(obj, s)] = s
for s in sub2:
idsub = geompy.GetSubShapeID(obj, s)
- if idsub in idsub1.keys():
+ if idsub in list(idsub1.keys()):
subList.append(s)
logging.debug("subList=%s", subList)
return subList
# -*- coding: utf-8 -*-
import logging
-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
def compoundFromList(elements, nom=None):
"""
import logging
-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 sortEdges import sortEdges
+from .sortEdges import sortEdges
def construitEdgesRadialesDebouchantes(idisklim, idiskout, gptsdisks, raydisks,
facesPipePeau, edgeRadFacePipePeau, nbsegCercle):
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:
import logging
-from geomsmesh import geompy
-from geomsmesh import smesh
+from .geomsmesh import geompy
+from .geomsmesh import smesh
import SMESH
def construitMaillagePipe(gptsdisks, idisklim, nbsegCercle, nbsegRad):
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from checkDecoupePartition import checkDecoupePartition
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .checkDecoupePartition import checkDecoupePartition
# -----------------------------------------------------------------------------
# --- peau et face de fissure
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from projettePointSurCourbe import projettePointSurCourbe
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .projettePointSurCourbe import projettePointSurCourbe
def creePointsPipePeau(listEdges, idFacesDebouchantes, idFillingFromBout,
ptEdgeFond, ptFisExtPi, edCircPeau, gptsdisks, idisklim, nbsegRad):
# -*- 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
# -----------------------------------------------------------------------------
# ---
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,
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- crée zone géométrique défaut a partir d'un filling
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from prolongeVertices import prolongeVertices
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .prolongeVertices import prolongeVertices
# -----------------------------------------------------------------------------
# --- zone de defaut, constructions geometrique avec CAO d'origine
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
import math
-from distance2 import distance2
+from .distance2 import distance2
import traceback
-from fissError import fissError
+from .fissError import fissError
# -----------------------------------------------------------------------------
# --- zone de defaut extraite du maillage
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- éliminer les doublons d'une liste de subshapes
idsubs = {}
for sub in subshapes:
subid = geompy.GetSubShapeID(obj, sub)
- if subid in idsubs.keys():
+ if subid in list(idsubs.keys()):
idsubs[subid].append(sub)
else:
idsubs[subid] = [sub]
shortList = []
- for k, v in idsubs.iteritems():
+ for k, v in idsubs.items():
shortList.append(v[0])
logging.debug("shortList=%s", shortList)
return shortList
import logging
-from geomsmesh import geompy
-from whichSideVertex import whichSideVertex
+from .geomsmesh import geompy
+from .whichSideVertex import whichSideVertex
def elimineExtremitesPipe(ptEdgeFond, facesDefaut, centres, gptsdisks, nbsegCercle):
"""
import logging
import math
-from geomsmesh import geompy
-from triedreBase import triedreBase
+from .geomsmesh import geompy
+from .triedreBase import triedreBase
O, OX, OY, OZ = triedreBase()
# -----------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import logging
-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
-from whichSide import whichSide
+from .whichSide import whichSide
# -----------------------------------------------------------------------------
# --- renvoie l'extraction des shapes d'un objet selon leur position par rapport à la face.
# -*- coding: utf-8 -*-
import logging
-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
-from whichSideMulti import whichSideMulti
+from .whichSideMulti import whichSideMulti
# -----------------------------------------------------------------------------
# --- renvoie l'extraction des shapes d'un objet selon leur position par rapport à la face.
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- TORE
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- faces fissure dans et hors tore, et edges face hors tore
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- identification des faces tore et fissure dans le solide hors tore du bloc partitionné
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from extractionOrientee import extractionOrientee
-from getSubshapeIds import getSubshapeIds
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .extractionOrientee import extractionOrientee
+from .getSubshapeIds import getSubshapeIds
# -----------------------------------------------------------------------------
# --- TORE
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- trouver les vertices extremites d'un wire
normals += [n1, n0]
for i, sub in enumerate(vertices):
subid = geompy.GetSubShapeID(aWire, sub)
- if subid in idsubs.keys():
+ if subid in list(idsubs.keys()):
idsubs[subid].append(sub)
else:
idsubs[subid] = [sub]
name='norm%d'%i
geomPublishInFather(initLog.debug, aWire, normals[i], name)
logging.debug("idsubs: %s", idsubs)
- for k, v in idsubs.iteritems():
+ for k, v in idsubs.items():
if len(v) == 1:
shortList.append(v[0])
if getNormals:
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- trouver les vertices intermediaires d'un wire
normals += [n1, n0]
for i, sub in enumerate(vertices):
subid = geompy.GetSubShapeID(aWire, sub)
- if subid in idsubs.keys():
+ if subid in list(idsubs.keys()):
idsubs[subid].append(sub)
else:
idsubs[subid] = [sub]
idnorm[subid] = normals[i]
name='norm%d'%i
geomPublishInFather(initLog.debug, aWire, normals[i], name)
- for k, v in idsubs.iteritems():
+ for k, v in idsubs.items():
if len(v) > 1:
shortList.append(v[0])
if getNormals:
# -*- coding: utf-8 -*-
-from geomsmesh import geompy, smesh
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
+from .geomsmesh import geompy, smesh
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
import math
import GEOM
#import NETGENPlugin
import logging
-from fissureGenerique import fissureGenerique
+from .fissureGenerique import fissureGenerique
-from triedreBase import triedreBase
-from genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
-from creeZoneDefautDansObjetSain import creeZoneDefautDansObjetSain
-from construitFissureGenerale import construitFissureGenerale
-from sortEdges import sortEdges
+from .triedreBase import triedreBase
+from .genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
+from .creeZoneDefautDansObjetSain import creeZoneDefautDansObjetSain
+from .construitFissureGenerale import construitFissureGenerale
+from .sortEdges import sortEdges
O, OX, OY, OZ = triedreBase()
externe = shapeFissureParams['externe']
lgInfluence = shapeFissureParams['lgInfluence']
self.elliptique = False
- if shapeFissureParams.has_key('elliptique'):
+ if 'elliptique' in shapeFissureParams:
self.elliptique = shapeFissureParams['elliptique']
"""
import logging
-from geomsmesh import geompy
-from geomsmesh import smesh
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
+from .geomsmesh import geompy
+from .geomsmesh import smesh
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
import GEOM
import SMESH
-from listOfExtraFunctions import createNewMeshesFromCorner
-from listOfExtraFunctions import createLinesFromMesh
+from .listOfExtraFunctions import createNewMeshesFromCorner
+from .listOfExtraFunctions import createLinesFromMesh
# -----------------------------------------------------------------------------
# --- groupe de quadrangles de face transformé en face géométrique par filling
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-
-from toreFissure import toreFissure
-from ellipsoideDefaut import ellipsoideDefaut
-from rotTrans import rotTrans
-from genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+
+from .toreFissure import toreFissure
+from .ellipsoideDefaut import ellipsoideDefaut
+from .rotTrans import rotTrans
+from .genereMeshCalculZoneDefaut import genereMeshCalculZoneDefaut
# -----------------------------------------------------------------------------
# --- création élements géométriques fissure elliptique
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import smesh
+from .geomsmesh import smesh
from salome.smesh import smeshBuilder
# -----------------------------------------------------------------------------
import logging
#logging.info('start')
-import initLog
+from . import initLog
import salome
salome.salome_init()
# -*- coding: utf-8 -*-
import logging
-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 bisect
publie = False
logging.debug('start')
nomRep = '.'
- if maillageFissureParams.has_key('nomRep'):
+ if 'nomRep' in maillageFissureParams:
nomRep = maillageFissureParams['nomRep']
nomFicFissure = maillageFissureParams['nomFicFissure']
if maillage is not None:
mesures = maillage.GetMeshInfo()
d= {}
- for key, value in mesures.iteritems():
+ for key, value in mesures.items():
logging.debug( "key: %s value: %s", key, value)
d[str(key)] = value
logging.debug("dico mesures %s", d)
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- transformation d'une liste de subshapes en une liste d'Id
import logging
-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
-from substractSubShapes import substractSubShapes
+from .substractSubShapes import substractSubShapes
def identifieEdgesPeau(edgesFissExtPipe,verticesPipePeau, facePeau, facesPeauSorted,
edgesPeauFondIn, fillingFaceExterne, aretesVivesC, aretesVivesCoupees):
import logging
import math
-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 traceback
-from fissError import fissError
+from .fissError import fissError
-from produitMixte import produitMixte
-from whichSide import whichSide
+from .produitMixte import produitMixte
+from .whichSide import whichSide
def identifieElementsDebouchants(ifil, facesDefaut, partitionPeauFissFond,
edgesFondIn, edgesFondFiss, wireFondFiss,
import logging
-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
-from extractionOrientee import extractionOrientee
-from extractionOrienteeMulti import extractionOrienteeMulti
+from .extractionOrientee import extractionOrientee
+from .extractionOrienteeMulti import extractionOrienteeMulti
def identifieElementsFissure(ifil, facesDefaut, partitionPeauFissFond,
edgesPipeFiss, edgesFondFiss, aretesVivesC,
import logging
-from identifieElementsFissure import identifieElementsFissure
-from identifieElementsDebouchants import identifieElementsDebouchants
-from trouveEdgesFissPeau import trouveEdgesFissPeau
-from identifieFacesPeau import identifieFacesPeau
-from identifieEdgesPeau import identifieEdgesPeau
+from .identifieElementsFissure import identifieElementsFissure
+from .identifieElementsDebouchants import identifieElementsDebouchants
+from .trouveEdgesFissPeau import trouveEdgesFissPeau
+from .identifieFacesPeau import identifieFacesPeau
+from .identifieEdgesPeau import identifieEdgesPeau
def identifieElementsGeometriquesPeau(ifil, partitionPeauFissFond, edgesPipeFiss,
edgesFondFiss, wireFondFiss, aretesVivesC,
import logging
-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
def identifieFacesEdgesFissureExterne(fsFissuExt, edFisExtPe, edFisExtPi, edgesPipeFiss):
"""
import logging
-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
-from sortFaces import sortFaces
-from extractionOrientee import extractionOrientee
+from .sortFaces import sortFaces
+from .extractionOrientee import extractionOrientee
def identifieFacesPeau(ifil, verticesPipePeau, facesOnside, wireFondFiss,
verticesEdgesFondIn, pipexts, cercles,
"""
creation nouvelle etude salome
"""
- import geomsmesh
+ from . import geomsmesh
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
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:
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
import logging
import SMESH
-from geomsmesh import smesh
+from .geomsmesh import smesh
def lookForCorner(maillageAScanner):
import logging
-from geomsmesh import geompy
-from geomsmesh import smesh
+from .geomsmesh import geompy
+from .geomsmesh import smesh
import SMESH
-from putName import putName
+from .putName import putName
def mailleAretesEtJonction(internalBoundary, aretesVivesCoupees, lgAretesVives):
"""
import logging
-from geomsmesh import geompy
-from geomsmesh import smesh
+from .geomsmesh import geompy
+from .geomsmesh import smesh
from salome.smesh import smeshBuilder
import SMESH
-from putName import putName
+from .putName import putName
def mailleFacesFissure(faceFissureExterne, edgesPipeFissureExterneC, edgesPeauFissureExterneC,
meshPipeGroups, areteFaceFissure, rayonPipe, nbsegRad):
import logging
-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
-from putName import putName
+from .putName import putName
def mailleFacesPeau(partitionsPeauFissFond, idFillingFromBout, facesDefaut,
facesPeaux, edCircPeau, ptCircPeau, gpedgeBord, gpedgeVifs, edFissPeau,
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import smesh
+from .geomsmesh import geompy
+from .geomsmesh import smesh
from salome.smesh import smeshBuilder
import SMESH
from salome.StdMeshers import StdMeshersBuilder
-from putName import putName
+from .putName import putName
# -----------------------------------------------------------------------------
# --- maillage du bloc partitionne
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- trouver les vertices intermediaires d'un wire
idverts[(i,1)] = verts[0]
idsubs = {}
- for kv, sub in idverts.iteritems():
+ for kv, sub in idverts.items():
subid = geompy.GetSubShapeID(aWire, sub)
- if subid in idsubs.keys():
+ if subid in list(idsubs.keys()):
idsubs[subid].append(kv)
else:
idsubs[subid] = [kv]
debut = -1
fin = -1
- for k, kvs in idsubs.iteritems():
+ for k, kvs in idsubs.items():
if len(kvs) == 1: # une extremité
kv = kvs[0]
if kv[1] == 0:
logging.debug("nombre d'edges: %s, indice edge début: %s, fin: %s",len(edges), debut, fin)
if debut < 0:
logging.critical("les edges du wire ne sont pas orientées dans le même sens: pas de début trouvé")
- return edges, range(len(edges))
+ return edges, list(range(len(edges)))
orderedList = [debut]
while len(orderedList) < len(edges):
bout = orderedList[-1]
vertex = idverts[(bout,1)]
- for k, v in idverts.iteritems():
+ for k, v in idverts.items():
if k[0] not in orderedList:
if geompy.MinDistance(vertex, v) < 1.e-4:
if k[1] == 0:
break
else:
logging.critical("les edges du wire ne sont pas orientées dans le même sens: une edge à l'envers")
- return edges, range(len(edges))
+ return edges, list(range(len(edges)))
logging.debug("liste des edges ordonnées selon le sens de parcours: %s", orderedList)
- accessList = range(len(orderedList))
+ accessList = list(range(len(orderedList)))
for i,k in enumerate(orderedList):
accessList[k] = i
logging.info("position ordonnée des edges selon le sens de parcours: %s", accessList)
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- partition du bloc defaut par generatrice, tore et plan fissure
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- partition volume sain et bloc, face du bloc recevant la fissure
import math
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from findWireEndVertices import findWireEndVertices
-from prolongeWire import prolongeWire
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .findWireEndVertices import findWireEndVertices
+from .prolongeWire import prolongeWire
import traceback
-from fissError import fissError
+from .fissError import fissError
def partitionneFissureParPipe(shapesFissure, elementsDefaut, rayonPipe):
"""
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import smesh
+from .geomsmesh import smesh
import SMESH
import traceback
-from fissError import fissError
+from .fissError import fissError
-from listOfExtraFunctions import lookForCorner
-from fusionMaillageAttributionDefaut import fusionMaillageDefaut
+from .listOfExtraFunctions import lookForCorner
+from .fusionMaillageAttributionDefaut import fusionMaillageDefaut
# -----------------------------------------------------------------------------
# --- peau interne du defaut dans le maillage sain
# --- Le groupe ZoneDefaut ne doit contenir que des Hexaèdres"
info=maillageSain.GetMeshInfo(zoneDefaut)
- keys = info.keys(); keys.sort()
+ keys = list(info.keys()); keys.sort()
nbelem=0
nbhexa=0
for i in keys:
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- calcul de produit mixte pour orientation
# -*- coding: utf-8 -*-
-from geomsmesh import geompy
+from .geomsmesh import geompy
import logging
import math
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- prolongation des segments extremité des polylines, pour la découpe
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from orderEdgesFromWire import orderEdgesFromWire
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .orderEdgesFromWire import orderEdgesFromWire
# -----------------------------------------------------------------------------
# --- prolongation d'un wire par deux segments tangents
uneSeuleEdge = True
edgesBout = []
for i, v1 in enumerate(extrem):
- exts = [geompy.MakeTranslationVectorDistance(v1, norms[i], l) for l in (-long, long)]
+ exts = [geompy.MakeTranslationVectorDistance(v1, norms[i], l) for l in (-int, int)]
dists = [(geompy.MinDistance(v, aWire), i , v) for i, v in enumerate(exts)]
dists.sort()
v2 = dists[-1][-1]
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- recherche et classement des edges du tore par propagate
# -*- coding: utf-8 -*-
-from geomsmesh import smesh
+from .geomsmesh import smesh
# -----------------------------------------------------------------------------
# --- nommage des objets mesh (algorithme, hypothèse, subMesh)
# -*- coding: utf-8 -*-
import logging
-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
import math
import numpy as np
logging.info("start")
isVecteurDefaut = False
- if shapeFissureParams.has_key('vecteurDefaut'):
+ if 'vecteurDefaut' in shapeFissureParams:
isVecteurDefaut = True
vecteurDefaut = shapeFissureParams['vecteurDefaut']
h = e/(np.sqrt(f*g)) # cosinus
ruptureX = h < cosmin # True si angle > reference
logging.debug("matrice de rupture X: \n%s",ruptureX)
- rupX = filter(lambda x: np.prod(ruptureX[:,x]), range(len(nodeline)-2))
+ rupX = [x for x in range(len(nodeline)-2) if np.prod(ruptureX[:,x])]
logging.debug("colonnes de rupture: %s",rupX)
# recherche d'angles supérieurs a un seuil sur une colonne : angle entre deux vecteurs successifs
vecy = mat[ 1:, :, :] - mat[:-1, :, :] # vecteurs selon direction "y"
h = e/(np.sqrt(f*g)) # cosinus
ruptureY = h < cosmin # True si angle > reference
logging.debug("matrice de rupture Y: \n%s",ruptureY)
- rupY = filter(lambda x: np.prod(ruptureY[x, :]), range(len(nodelines)-2))
+ rupY = [x for x in range(len(nodelines)-2) if np.prod(ruptureY[x, :])]
logging.debug("lignes de rupture: %s",rupY)
if (len(rupX)*len(rupY)) > 0:
logging.critical("""Cas non traité: présence d'angles vifs dans 2 directions,
pointIn_y = 0.0
pointIn_z = 0.0
pointExplicite = False
- if shapeFissureParams.has_key('pointIn_x'):
+ if 'pointIn_x' in shapeFissureParams:
pointExplicite = True
pointIn_x = shapeFissureParams['pointIn_x']
- if shapeFissureParams.has_key('pointIn_y'):
+ if 'pointIn_y' in shapeFissureParams:
pointExplicite = True
pointIn_y = shapeFissureParams['pointIn_y']
- if shapeFissureParams.has_key('pointIn_z'):
+ if 'pointIn_z' in shapeFissureParams:
pointExplicite = True
pointIn_z = shapeFissureParams['pointIn_z']
if pointExplicite:
logging.debug("orientation filling par point intérieur %s", (pointIn_x, pointIn_y, pointIn_z))
vecteurDefaut = geompy.MakeVector(cdg, vertex)
- if shapeFissureParams.has_key('convexe'):
+ if 'convexe' in shapeFissureParams:
isConvexe = shapeFissureParams['convexe']
logging.debug("orientation filling par indication de convexité %s", isConvexe)
cdg = geompy.MakeCDG(filling)
# -*- coding: utf-8 -*-
import logging
-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
import math
import numpy as np
logging.info("start")
isVecteurDefaut = False
- if shapeFissureParams.has_key('vecteurDefaut'):
+ if 'vecteurDefaut' in shapeFissureParams:
isVecteurDefaut = True
vecteurDefaut = shapeFissureParams['vecteurDefaut']
h = e/(np.sqrt(f*g)) # cosinus
ruptureX = h < cosmin # True si angle > reference
logging.debug("matrice de rupture X: \n%s",ruptureX)
- rupX = filter(lambda x: np.prod(ruptureX[:,x]), range(len(nodeline)-2))
+ rupX = [x for x in range(len(nodeline)-2) if np.prod(ruptureX[:,x])]
logging.debug("colonnes de rupture: %s",rupX)
# recherche d'angles supérieurs a un seuil sur une colonne : angle entre deux vecteurs successifs
vecy = mat[ 1:, :, :] - mat[:-1, :, :] # vecteurs selon direction "y"
h = e/(np.sqrt(f*g)) # cosinus
ruptureY = h < cosmin # True si angle > reference
logging.debug("matrice de rupture Y: \n%s",ruptureY)
- rupY = filter(lambda x: np.prod(ruptureY[x, :]), range(len(nodelines)-2))
+ rupY = [x for x in range(len(nodelines)-2) if np.prod(ruptureY[x, :])]
logging.debug("lignes de rupture: %s",rupY)
if (len(rupX)*len(rupY)) > 0:
logging.critical("""Cas non traité: présence d'angles vifs dans 2 directions,
pointIn_y = 0.0
pointIn_z = 0.0
pointExplicite = False
- if shapeFissureParams.has_key('pointIn_x'):
+ if 'pointIn_x' in shapeFissureParams:
pointExplicite = True
pointIn_x = shapeFissureParams['pointIn_x']
- if shapeFissureParams.has_key('pointIn_y'):
+ if 'pointIn_y' in shapeFissureParams:
pointExplicite = True
pointIn_y = shapeFissureParams['pointIn_y']
- if shapeFissureParams.has_key('pointIn_z'):
+ if 'pointIn_z' in shapeFissureParams:
pointExplicite = True
pointIn_z = shapeFissureParams['pointIn_z']
if pointExplicite:
logging.debug("orientation filling par point intérieur %s", (pointIn_x, pointIn_y, pointIn_z))
vecteurDefaut = geompy.MakeVector(cdg, vertex)
- if shapeFissureParams.has_key('convexe'):
+ if 'convexe' in shapeFissureParams:
isConvexe = shapeFissureParams['convexe']
logging.debug("orientation filling par indication de convexité %s", isConvexe)
cdg = geompy.MakeCDG(filling)
"""
import logging
-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 listOfExtraFunctions import createNewMeshesFromCorner
-from listOfExtraFunctions import createLinesFromMesh
+from .listOfExtraFunctions import createNewMeshesFromCorner
+from .listOfExtraFunctions import createLinesFromMesh
# -----------------------------------------------------------------------------
# --- groupe de quadrangles de face transformé en face géométrique par filling
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import smesh
+from .geomsmesh import smesh
import SMESH
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- maillage complet et fissure
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
-from geomsmesh import geomPublish
-from geomsmesh import geomPublishInFather
-import initLog
-from sortFaces import sortFaces
+from .geomsmesh import geompy
+from .geomsmesh import geomPublish
+from .geomsmesh import geomPublishInFather
+from . import initLog
+from .sortFaces import sortFaces
import traceback
-from fissError import fissError
+from .fissError import fissError
def restreintFaceFissure(shapeDefaut, facesDefaut, pointInterne):
"""
# -*- coding: utf-8 -*-
import logging
-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 math
-from triedreBase import triedreBase
+from .triedreBase import triedreBase
O, OX, OY, OZ = triedreBase()
# -----------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- construction d'une shape de dectection des éléments à modifier suite à la la duplication des noeuds de la face fissure (d'un coté de la face)
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- identification des shapes modifiées par la duplication des noeuds de la face fissure (d'un coté de la face)
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- tri par longueur d'edges
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- tri par surface de faces
# -*- coding: utf-8 -*-
import logging
-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
# -----------------------------------------------------------------------------
# --- tri par longueur des 3 generatrices
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- tri par volume de solides
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- substract a list of subShapes from another
idToremove[geompy.GetSubShapeID(obj, s)] = s
for s in subs:
idsub = geompy.GetSubShapeID(obj, s)
- if idsub not in idToremove.keys():
+ if idsub not in list(idToremove.keys()):
subList.append(s)
logging.debug("subList=%s", subList)
return subList
# -*- coding: utf-8 -*-
import logging
-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 math
-from triedreBase import triedreBase
+from .triedreBase import triedreBase
O, OX, OY, OZ = triedreBase()
# -*- coding: utf-8 -*-
import logging
-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
# --- origine et vecteurs de base
import logging
-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
def trouveEdgesFissPeau(facesInside, facesOnside, edgesPipeIn, edgesFondIn, partitionPeauFissFond, edgesFissExtPeau):
"""
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- calcul de la position d'une shape par rapport à une face (dessus, dessous, sur la surface même)
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- calcul de la position d'une shape par rapport à une face (dessus, dessous, sur la surface même)
# -*- coding: utf-8 -*-
import logging
-from geomsmesh import geompy
+from .geomsmesh import geompy
# -----------------------------------------------------------------------------
# --- calcul de la position d'une shape par rapport à une face (dessus, dessous, sur la surface même)
pointIn_x : optionnel coordonnées x d'un point dans le solide, pas trop loin du centre du fond de fissure (idem y,z)
externe : True : fissure face externe, False : fissure face interne
"""
- print "setParamShapeFissure", self.nomCas
+ print("setParamShapeFissure", self.nomCas)
self.shapeFissureParams = dict(profondeur = self.dico['profondeur'],
rayonPipe = self.dico['rayonTore'],
lenSegPipe = self.dico['lenSegPipe'],
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):
f = open(filedef, 'r')
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)")
f.close()
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()
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
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):
f = open(filedef, 'r')
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'
f.close()
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()
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
import SALOME_ModuleCatalog
catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
if not catalog:
- raise RuntimeError, "Can't accesss module catalog"
+ raise RuntimeError("Can't accesss module catalog")
filename = getSpadderCatalogFilename()
catalog.ImportXmlCatalogFile(filename)
from salome.kernel import services
- print "The list of SALOME components is now:"
- print services.getComponentList()
+ print("The list of SALOME components is now:")
+ print(services.getComponentList())
#
import sys, os
-import ConfigParser
+import configparser
from MESHJOB import ConfigParameter
from salome.kernel.uiexception import AdminException, UiException
self.__configFilename = None
try:
smeshpath=os.environ["SMESH_ROOT_DIR"]
- except KeyError, ex:
+ except KeyError as ex:
raise AdminException("You should define the variable SMESH_ROOT_DIR")
pluginspath = os.path.join(smeshpath,CONFIG_RELPATH)
msg = "The configuration file %s can't be found in the SMESH plugins path %s"
raise AdminException(msg%(CONFIG_FILENAME,pluginspath))
- print "The configuration file is : %s"%self.__configFilename
- self.__configparser = ConfigParser.RawConfigParser()
+ print("The configuration file is : %s"%self.__configFilename)
+ self.__configparser = configparser.RawConfigParser()
try:
self.__configparser.read(self.__configFilename)
- except ConfigParser.ParsingError, ex:
+ except configparser.ParsingError as ex:
raise AdminException(ex.message)
def getLocalConfig(self):
return defaultType
def printConfig(config):
- print "PADDER CONFIGURATION:"
- print "\tconfig.resname = %s"%config.resname
- print "\tconfig.binpath = %s"%config.binpath
- print "\tconfig.envpath = %s"%config.envpath
+ print("PADDER CONFIGURATION:")
+ print("\tconfig.resname = %s"%config.resname)
+ print("\tconfig.binpath = %s"%config.binpath)
+ print("\tconfig.envpath = %s"%config.envpath)
def getPadderTestDir(config):
"""
try:
configReader = ConfigReader()
defaultConfig = configReader.getDefaultConfig()
- print defaultConfig.resname
- print defaultConfig.binpath
- print defaultConfig.envpath
- except Exception, ex:
+ print(defaultConfig.resname)
+ print(defaultConfig.binpath)
+ print(defaultConfig.envpath)
+ except Exception as ex:
sys.stderr.write('ERROR: %s\n' % str(ex))
return False
try:
configReader = ConfigReader()
defaultConfig = configReader.getDefaultConfig()
- except UiException, err:
- print 'ERROR: %s' % str(err)
+ except UiException as err:
+ print('ERROR: %s' % str(err))
return True
return False
from qtsalome import QIcon, QStandardItemModel, QStandardItem, QMessageBox, pyqtSignal
from inputframe_ui import Ui_InputFrame
-from inputdata import InputData
+from .inputdata import InputData
DEBUG_MODE=True
GROUPNAME_MAXLENGTH=8
"""
# if the entry already exists, we remove it to replace by a
# new one
- if self.__dictInputData.has_key(meshName):
+ if meshName in self.__dictInputData:
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, listInputData=[]):
"""
# Note that the values() function returns a copy of the list
# of values.
- return self.__dictInputData.values()
+ return list(self.__dictInputData.values())
def checkData(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
-from inputdata import InputData
+from .inputdialog import InputDialog
+from .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
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
from salome.kernel.uiexception import UiException
try:
dialog=plugindialog.getDialog()
- except UiException, err:
+ except UiException as err:
from qtsalome import QMessageBox
QMessageBox.critical(None,"An error occurs during PADDER configuration",
err.getUIMessage())
jobid = component.initialize(meshJobFileList, meshJobParameterList, configId)
if jobid<0:
msg = component.getLastErrorMessage()
- print "ERR: %s"%msg
+ print("ERR: %s"%msg)
sys.exit(1)
created = False
nbiter = 0
while not created:
state = component.getState(jobid)
- print "MeshJobManager ["+str(nbiter)+"] : state = "+str(state)
+ print("MeshJobManager ["+str(nbiter)+"] : state = "+str(state))
if state == "CREATED":
created = True
time.sleep(0.5)
ok=component.start(jobid)
if not ok:
msg = component.getLastErrorMessage()
- print "ERR: %s"%msg
+ print("ERR: %s"%msg)
sys.exit(1)
-print "job started: %s"%ok
+print("job started: %s"%ok)
#
# This part illustrates how you can follow the execution of the job.
nbiter = 0
while not ended:
state = component.getState(jobid)
- print "MeshJobManager ["+str(nbiter)+"] : state = "+str(state)
+ print("MeshJobManager ["+str(nbiter)+"] : state = "+str(state))
if state not in run_states:
ended=True
time.sleep(0.5)
nbiter+=1
if state not in end_states:
- print "ERR: jobid = "+str(jobid)+" ended abnormally with state="+str(state)
+ print("ERR: jobid = "+str(jobid)+" ended abnormally with state="+str(state))
msg = component.getLastErrorMessage()
- print "ERR: %s"%msg
+ print("ERR: %s"%msg)
else:
- print "OK: jobid = "+str(jobid)+" ended with state="+str(state)
+ print("OK: jobid = "+str(jobid)+" ended with state="+str(state))
meshJobResults = component.finalize(jobid)
- print meshJobResults
+ print(meshJobResults)
if meshJobResults.status is not True:
- print "ERR: the results are not OK: %s"%component.getLastErrorMessage()
- print "ERR: see log files in %s"%meshJobResults.results_dirname
+ print("ERR: the results are not OK: %s"%component.getLastErrorMessage())
+ print("ERR: see log files in %s"%meshJobResults.results_dirname)
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)
-print "Test completed : OK"
+print("Test completed : OK")