plugin_list.append("AdvancedGEOM")
# find additional plugins
- 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
plugin_list.append(plugin)
# add paths of 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)
# in one plane
Angle = geompy.GetAngle(OX, OXY)
-print "\nAngle between OX and OXY = ", Angle
+print("\nAngle between OX and OXY = ", Angle)
if math.fabs(Angle - 45.0) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 45.0"
+ print(" Error: returned angle is", Angle, "while must be 45.0")
pass
Angle = geompy.GetAngleRadians(OX, OXY)
-print "\nAngle between OX and OXY in radians = ", Angle
+print("\nAngle between OX and OXY in radians = ", Angle)
if math.fabs(Angle - math.pi/4) > 1e-05:
- print " Error: returned angle is", Angle, "while must be pi/4"
+ print(" Error: returned angle is", Angle, "while must be pi/4")
pass
Angle = geompy.GetAngleVectors(OX, OXY, True)
-print "\nAngle between vectors OX and OXY = ", Angle
+print("\nAngle between vectors OX and OXY = ", Angle)
if math.fabs(Angle - 45.0) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 45.0"
+ print(" Error: returned angle is", Angle, "while must be 45.0")
pass
Angle = geompy.GetAngleRadiansVectors(OX, OXY, False)
-print "\nBig angle between vectors OX and OXY in radians = ", Angle
+print("\nBig angle between vectors OX and OXY in radians = ", Angle)
if math.fabs(Angle - math.pi*7./4.) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 7*pi/4"
+ print(" Error: returned angle is", Angle, "while must be 7*pi/4")
pass
# not in one plane
OXY_shift = geompy.MakeTranslation(OXY,10,-10,20)
Angle = geompy.GetAngle(OX, OXY_shift)
-print "\nAngle between OX and OXY_shift = ", Angle
+print("\nAngle between OX and OXY_shift = ", Angle)
if math.fabs(Angle - 45.0) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 45.0"
+ print(" Error: returned angle is", Angle, "while must be 45.0")
pass
# not linear
# create a box
box = geompy.MakeBoxDXDYDZ(100,30,100)
props = geompy.BasicProperties(box)
-print "\nBox 100x30x100 Basic Properties:"
-print " Wires length: ", props[0]
-print " Surface area: ", props[1]
-print " Volume : ", props[2]
+print("\nBox 100x30x100 Basic Properties:")
+print(" Wires length: ", props[0])
+print(" Surface area: ", props[1])
+print(" Volume : ", props[2])
length = math.sqrt((props[0] - 1840)*(props[0] - 1840))
area = math.sqrt((props[1] - 32000)*(props[1] - 32000))
volume = math.sqrt((props[2] - 300000)*(props[2] - 300000))
if length > 1e-7 or area > 1e-7 or volume > 1e-7:
- print "While must be:"
- print " Wires length: ", 1840
- print " Surface area: ", 32000
- print " Volume : ", 300000.
+ print("While must be:")
+ print(" Wires length: ", 1840)
+ print(" Surface area: ", 32000)
+ print(" Volume : ", 300000.)
geompy.addToStudy(check_box, "Box")
ii = 1
for chain in listChains:
- geompy.addToStudyInFather(check_box, chain, "propagation chain " + `ii`)
+ geompy.addToStudyInFather(check_box, chain, "propagation chain " + repr(ii))
ii = ii + 1
pass
box = geompy.MakeBoxDXDYDZ(100,30,100)
bb = geompy.BoundingBox(box)
-print "\nBounding Box of box 100x30x100:"
-print " Xmin = ", bb[0], ", Xmax = ", bb[1]
-print " Ymin = ", bb[2], ", Ymax = ", bb[3]
-print " Zmin = ", bb[4], ", Zmax = ", bb[5]
+print("\nBounding Box of box 100x30x100:")
+print(" Xmin = ", bb[0], ", Xmax = ", bb[1])
+print(" Ymin = ", bb[2], ", Ymax = ", bb[3])
+print(" Zmin = ", bb[4], ", Zmax = ", bb[5])
aBB = geompy.MakeBoundingBox(box)
box = geompy.MakeBoxDXDYDZ(100,30,100)
cm = geompy.MakeCDG(box)
if cm is None:
- raise RuntimeError, "MakeCDG(box) failed"
+ raise RuntimeError("MakeCDG(box) failed")
else:
- print "\nCentre of gravity of box has been successfully obtained:"
+ print("\nCentre of gravity of box has been successfully obtained:")
coords = geompy.PointCoordinates(cm)
- print "(", coords[0], ", ", coords[1], ", ", coords[2], ")"
+ print("(", coords[0], ", ", coords[1], ", ", coords[2], ")")
dx = math.sqrt((coords[0] - 50)*(coords[0] - 50))
dy = math.sqrt((coords[1] - 15)*(coords[1] - 15))
dz = math.sqrt((coords[2] - 50)*(coords[2] - 50))
if dx > 1e-7 or dy > 1e-7 or dz > 1e-7:
- print "But must be (50, 15, 50)"
+ print("But must be (50, 15, 50)")
glue = geompy.MakeGlueFaces(compound, tolerance)
IsValid = geompy.CheckCompoundOfBlocks(glue)
if IsValid == 0:
- raise RuntimeError, "Invalid compound created"
+ raise RuntimeError("Invalid compound created")
else:
- print "\nCompound is valid"
+ print("\nCompound is valid")
# check self-intersection
IsValid = geompy.CheckSelfIntersections(compound)
if not IsValid:
- print "Shape is self-intersected!"
+ print("Shape is self-intersected!")
else:
- print "No self-intersection detected in a shape"
+ print("No self-intersection detected in a shape")
# check self-intersection
IsValid = geompy.CheckSelfIntersectionsFast(compound)
if not IsValid:
- print "Shape is self-intersected!"
+ print("Shape is self-intersected!")
else:
- print "No self-intersection detected in a shape"
+ print("No self-intersection detected in a shape")
(IsValid, err) = geompy.CheckShape(box, 0, 2)
if IsValid == 0:
geompy.PrintShapeErrors(box, err)
- raise RuntimeError, "Invalid box created"
+ raise RuntimeError("Invalid box created")
else:
- print "\nBox is valid"
+ print("\nBox is valid")
isOk, res1, res2 = geompy.FastIntersect(box, cylinder)
if isOk == 0:
- raise RuntimeError, "No intersection!"
+ raise RuntimeError("No intersection!")
else:
- print "\nTwo lists of indexes of sub-shapes localize the intersection:"
- print res1, res2
+ print("\nTwo lists of indexes of sub-shapes localize the intersection:")
+ print(res1, res2)
# create two boxes with gap
Ver1 = geompy.MakeVertex(0, 0, 0)
isOk1, aRes1, aRes2 = geompy.FastIntersect(box1, box2, 1.)
if isOk1 == 0:
- raise RuntimeError, "No gaps!"
+ raise RuntimeError("No gaps!")
else:
- print "\nTwo lists of indexes of sub-shapes localize the gap:"
- print aRes1, aRes2
+ print("\nTwo lists of indexes of sub-shapes localize the gap:")
+ print(aRes1, aRes2)
fid = geompy.addToStudyInFather(cut, faces[fi], "Face %d" % (fi+1))
isSuccess, closedWires, openWires = geompy.GetFreeBoundary(faces[fi])
if isSuccess:
- print "Check free boudaries in face %d: OK" % (fi+1)
- print "-- Nb of closed boundaries = %d" % len(closedWires)
+ print("Check free boudaries in face %d: OK" % (fi+1))
+ print("-- Nb of closed boundaries = %d" % len(closedWires))
for wi in range(len(closedWires)):
wid = geompy.addToStudyInFather(faces[fi], closedWires[wi], "Closed wire %d" % (wi+1))
pass
- print "-- Nb of open boundaries = %d" % len(openWires)
+ print("-- Nb of open boundaries = %d" % len(openWires))
for wi in range(len(openWires)):
wid = geompy.addToStudyInFather(faces[fi], openWires[wi], "Open wire %d" % (wi+1))
pass
pass
else:
- print "Check free boudaries in face %d: KO" % (fi+1)
+ print("Check free boudaries in face %d: KO" % (fi+1))
pass
pass
# suppress the specified wire
result = geompy.GetFreeFacesIDs(cut_without_f_2)
-print "A number of free faces is ", len(result)
+print("A number of free faces is ", len(result))
# add objects in the study
all_faces = geompy.SubShapeAllSortedCentres(cut_without_f_2, geompy.ShapeType["FACE"])
# create a box
box = geompy.MakeBoxDXDYDZ(100,30,100)
In = geompy.Inertia(box)
-print "\nInertia matrix of box 100x30x100:"
-print " (", In[0], ", ", In[1], ", ", In[2], ")"
-print " (", In[3], ", ", In[4], ", ", In[5], ")"
-print " (", In[6], ", ", In[7], ", ", In[8], ")"
-print "Main moments of inertia of box 100x30x100:"
-print " Ix = ", In[9], ", Iy = ", In[10], ", Iz = ", In[11]
+print("\nInertia matrix of box 100x30x100:")
+print(" (", In[0], ", ", In[1], ", ", In[2], ")")
+print(" (", In[3], ", ", In[4], ", ", In[5], ")")
+print(" (", In[6], ", ", In[7], ", ", In[8], ")")
+print("Main moments of inertia of box 100x30x100:")
+print(" Ix = ", In[9], ", Iy = ", In[10], ", Iz = ", In[11])
geompy.addToStudy(v2, 'MinDist_%d_Curve_b'%(i+1))
# Get minimum distance
-print "Minimal distance between Curve_a and Curve_b is", geompy.MinDistance(Curve_a, Curve_b)
+print("Minimal distance between Curve_a and Curve_b is", geompy.MinDistance(Curve_a, Curve_b))
# Get minimum distance with components along axes
[aDist, DX, DY, DZ] = geompy.MinDistanceComponents(Curve_a, Curve_b)
-print "Minimal distance between Curve_a and Curve_b is (", DX, ",", DY, ",", DZ, ")"
+print("Minimal distance between Curve_a and Curve_b is (", DX, ",", DY, ",", DZ, ")")
face0 = faces[0]
vnorm = geompy.GetNormal(face0)
if vnorm is None:
- raise RuntimeError, "GetNormal(face0) failed"
+ raise RuntimeError("GetNormal(face0) failed")
else:
geompy.addToStudy(face0, "Face0")
geompy.addToStudy(vnorm, "Normale to Face0")
- print "\nNormale of face has been successfully obtained"
+ print("\nNormale of face has been successfully obtained")
def IsEqual(val1, val2): return (math.fabs(val1 - val2) < tolerance)
if IsEqual(coords[0], 15.) and IsEqual(coords[1], 23.) and IsEqual(coords[2], 80.):
- print "All values are OK."
+ print("All values are OK.")
else :
- print "Coordinates of point must be (15, 23, 80), but returned (",
- print coords[0], ", ", coords[1], ", ", coords[2], ")"
+ print("Coordinates of point must be (15, 23, 80), but returned (", end=' ')
+ print(coords[0], ", ", coords[1], ", ", coords[2], ")")
pass
theShape = geompy.MakePrismVecH(face, edge, 130)
# check the shape at the beginning
-print "Before ProcessShape:"
+print("Before ProcessShape:")
isValid = geompy.CheckShape(theShape)
if isValid == 0:
- print "The shape is not valid"
+ print("The shape is not valid")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
# process the Shape
Operators = ["FixShape"]
PS = geompy.ProcessShape(theShape, Operators, Parameters, Values)
# check the shape at the end
-print "After ProcessShape:"
+print("After ProcessShape:")
isValid = geompy.CheckShape(PS)
if isValid == 0:
- print "The shape is not valid"
- raise RuntimeError, "It seems, that the ProcessShape() has failed"
+ print("The shape is not valid")
+ raise RuntimeError("It seems, that the ProcessShape() has failed")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
# add in the study and display
Id_Shape = geompy.addToStudy(theShape, "Invalid Shape")
# create a box
box = geompy.MakeBoxDXDYDZ(100,30,100)
Toler = geompy.Tolerance(box)
-print "\nBox 100x30x100 tolerance:"
-print " Face min. tolerance: ", Toler[0]
-print " Face max. tolerance: ", Toler[1]
-print " Edge min. tolerance: ", Toler[2]
-print " Edge max. tolerance: ", Toler[3]
-print " Vertex min. tolerance: ", Toler[4]
-print " Vertex max. tolerance: ", Toler[5]
+print("\nBox 100x30x100 tolerance:")
+print(" Face min. tolerance: ", Toler[0])
+print(" Face max. tolerance: ", Toler[1])
+print(" Edge min. tolerance: ", Toler[2])
+print(" Edge max. tolerance: ", Toler[3])
+print(" Vertex min. tolerance: ", Toler[4])
+print(" Vertex max. tolerance: ", Toler[5])
# create a box
box = geompy.MakeBoxDXDYDZ(100,30,100)
Descr = geompy.WhatIs(box)
-print "\nBox 100x30x100 description:"
-print Descr
+print("\nBox 100x30x100 description:")
+print(Descr)
plugin_module_name = plugin_name + "Builder"
plugin_module = "salome.%s.%s" % (plugin_name, plugin_module_name)
import_str = "from salome.%s import %s" % (plugin_name, plugin_module_name)
- exec( import_str )
- exec( "import %s" % plugin_module )
- exec( "mod = %s" % plugin_module )
+ execLine = "from salome.%s import %s\nimport %s\nmod = %s" % (plugin_name, plugin_module_name,plugin_module,plugin_module)
+ print(execLine)
+ namespace = {}
+ exec( execLine , namespace)
functions = []
- for attr in dir( mod ):
+ for attr in dir( namespace["mod"] ):
if attr.startswith( '_' ): continue # skip an internal methods
- item = getattr( mod, attr )
+ item = getattr( namespace["mod"], attr )
if type( item ).__name__ == 'function':
if item not in functions:
functions.append( item )
static PyTypeObject PyStdOut_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* 0, */ /*ob_size*/
"PyOut", /*tp_name*/
sizeof(PyStdOut), /*tp_basicsize*/
0, /*tp_itemsize*/
salome.salome_init()
if studyId is None:
studyId = getActiveStudyId()
- if not _geompys.has_key(studyId):
+ if studyId not in _geompys:
from salome.geom import geomBuilder
study = salome.myStudyManager.GetStudyByID(studyId)
_geompys[studyId] = geomBuilder.New(study)
def TEST_getGeomObjectSelected():
tool = GeomStudyTools()
myGeomObject = tool.getGeomObjectSelected()
- print myGeomObject
+ print(myGeomObject)
## This test is a simple use case that illustrates how to create a
# GEOM shape in a SALOME session (create the GEOM object, put in in
expectedResult = "Sketcher:F 1.234 4.321:TT 2.234 5.321"
result = mysketcher.toString()
- print "sketcher=",mysketcher.toString()
+ print("sketcher=",mysketcher.toString())
if result == expectedResult:
- print "OK"
+ print("OK")
else:
- print "Not OK"
+ print("Not OK")
def TEST_usingGeom():
mysketcher = Sketcher()
self._studyEditor.studyId, meshGroup,
groupGeomObj, newparams)
element.addPart(part)
- except InvalidParameterError, e:
+ except InvalidParameterError as e:
logger.error("Invalid parameter error: %s" % e)
raise
except:
elif groupMailleParam is not None and meshGroupParam is None:
meshGroupParam = groupMailleParam
- if isinstance(meshGroupParam, types.StringTypes):
+ if isinstance(meshGroupParam, str):
meshGroupList = [meshGroupParam]
else:
meshGroupList = meshGroupParam
newshapes = newpart.baseShapesSet
# Check duplicate groups
- if self._parts.has_key(newpart.groupName):
+ if newpart.groupName in self._parts:
logger.warning('Mesh group "%s" is used several times in the '
'structural element. Only the last definition '
'will be used.' % newpart.groupName)
else:
# Check duplicate shapes
- intersect = newshapes.intersection(self._shapeDict.keys())
+ intersect = newshapes.intersection(list(self._shapeDict.keys()))
while len(intersect) > 0:
shape, = intersect
oldpartwithshape = self._shapeDict[shape]
:class:`~orientation.Orientation1D`.
"""
- if self._parts.has_key(meshGroup):
+ if meshGroup in self._parts:
self._parts[meshGroup].addOrientation(orientParams)
else:
logger.warning('Mesh group "%s" not found in structural element, '
"""
gg = salome.ImportComponentGUI("GEOM")
geompy = getGeompy(self._studyEditor.studyId)
- for part in self._parts.itervalues():
+ for part in self._parts.values():
# Build the structural element part
logger.debug("Building %s" % part)
try:
'times for the same mesh group, only the last '
'parameter will be used')
mydict = params.copy()
- if mydict.has_key("VECT_Y"):
+ if "VECT_Y" in mydict:
newVecCoords = mydict.pop("VECT_Y")
logger.debug("Setting orientation vector Y to %s" %
str(newVecCoords))
self._vectorYCoords = newVecCoords
self._angle = 0.0
- if mydict.has_key("ANGL_VRIL"):
+ if "ANGL_VRIL" in mydict:
newAngle = mydict.pop("ANGL_VRIL")
logger.debug("Setting orientation angle to %f" % newAngle)
self._angle = newAngle
logger = Logger("salome.geom.structelem.parts", color = termcolor.RED)
from salome.geom.geomtools import getGeompy
-import orientation
+from . import orientation
# Filling for the beams
FULL = "FULL"
if len(nameList) > 0:
paramName = nameList[0]
for name in nameList:
- if self._parameters.has_key(name):
+ if name in self._parameters:
self._paramUserName[paramName] = name
return self._parameters[name]
return default
"""
This method finds the user name for a parameter.
"""
- if self._paramUserName.has_key(paramName):
+ if paramName in self._paramUserName:
return self._paramUserName[paramName]
else:
return paramName
def __init__(self, studyId, groupName, groupGeomObj, parameters,
name = Beam.DEFAULT_NAME, color = None):
if color is None:
- if parameters.has_key("R1"): # variable section
+ if "R1" in parameters: # variable section
color = LIGHT_RED
else: # constant section
color = RED
def __init__(self, studyId, groupName, groupGeomObj, parameters,
name = Beam.DEFAULT_NAME, color = None):
if color is None:
- if parameters.has_key("HY1") or parameters.has_key("H1"):
+ if "HY1" in parameters or "H1" in parameters:
color = LIGHT_BLUE # variable section
else: # constant section
color = BLUE
several different names.
"""
for name in nameList:
- if parametersDict.has_key(name):
+ if name in parametersDict:
return parametersDict[name]
return default
parameters["HZ2"] = math.sqrt(12 * self.IY2 / self.A2)
if color is None:
- if parameters.has_key("IY1"): # variable section
+ if "IY1" in parameters: # variable section
color = LIGHT_GREEN
else: # constant section
color = GREEN
anOp = GetBREPPluginOperations(self)
anOp.ExportBREP(theObject, theFileName)
if anOp.IsDone() == 0:
- raise RuntimeError, "Export : " + anOp.GetErrorCode()
+ raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
# Get information about objects
hasInfo = geompy.hasObjectInfo()
-print "Check if GEOM module provides information about its objects: ", hasInfo
+print("Check if GEOM module provides information about its objects: ", hasInfo)
if hasInfo == True:
- print "Information about first object: ", geompy.getObjectInfo(salome.myStudyId, obj1_entry)
- print "Information about second object: ", geompy.getObjectInfo(salome.myStudyId, obj2_entry)
- print "Information about third object: ", geompy.getObjectInfo(salome.myStudyId, obj3_entry)
- print "Information about fourth object: ", geompy.getObjectInfo(salome.myStudyId, obj4_entry)
- print "Information about fifth object: ", geompy.getObjectInfo(salome.myStudyId, obj5_entry)
+ print("Information about first object: ", geompy.getObjectInfo(salome.myStudyId, obj1_entry))
+ print("Information about second object: ", geompy.getObjectInfo(salome.myStudyId, obj2_entry))
+ print("Information about third object: ", geompy.getObjectInfo(salome.myStudyId, obj3_entry))
+ print("Information about fourth object: ", geompy.getObjectInfo(salome.myStudyId, obj4_entry))
+ print("Information about fifth object: ", geompy.getObjectInfo(salome.myStudyId, obj5_entry))
salome.sg.updateObjBrowser(True)
nbFaces = geompy.ShapesOp.NumberOfFaces(Prism1)
if nbFaces == 6:
- print "Prism 1 is a hexahedral solid"
+ print("Prism 1 is a hexahedral solid")
else:
- print "Prism 1 is not a hexahedral solid"
+ print("Prism 1 is not a hexahedral solid")
Prism1_faces = geompy.SubShapeAllSortedCentres(Prism1, geompy.ShapeType["FACE"])
ii = 1
try:
Block3h = geompy.GetBlockByParts(Handle, [Face12h, Face22h])
except RuntimeError:
- print "ERROR: BlocksOp.GetBlockByParts() failed : ", geompy.BlocksOp.GetErrorCode()
+ print("ERROR: BlocksOp.GetBlockByParts() failed : ", geompy.BlocksOp.GetErrorCode())
else:
id_block3h = geompy.addToStudyInFather(Handle, Block3h, "Block 3 of Handle")
isCompOfBlocks6 = geompy.CheckCompoundOfBlocks(Spanner)
if isCompOfBlocks6 == 0:
- print "Spanner is not a compound of hexahedral solids"
+ print("Spanner is not a compound of hexahedral solids")
(NonBlocks, NonQuads) = geompy.GetNonBlocks(Spanner)
if NonBlocks is not None:
geompy.addToStudyInFather(Spanner, NonBlocks, "Group of non-hexahedral solids")
if NonQuads is not None:
geompy.addToStudyInFather(Spanner, NonQuads, "Group of non-quadrangular faces")
else:
- print "Spanner is a compound of hexahedral solids"
+ print("Spanner is a compound of hexahedral solids")
if isBlocksTest == 1:
- print "##################### Test More #####################"
+ print("##################### Test More #####################")
### Get Blocks 4 and 5 from the spanner ###
id_MRot_tr = geompy.addToStudy(MRot_tr, "Multi-rotated block 5")
if isMRot2D == 0:
- print "2D Multi Transformation failed"
+ print("2D Multi Transformation failed")
### Get one face of the Gear ###
id_face_g_1 = geompy.addToStudyInFather(Gear, Face_g_1, "Face of Gear by four points")
edgesNb = geompy.ShapesOp.NumberOfEdges(Face_g_1)
- print "Face of Gear has ", edgesNb, " edges"
+ print("Face of Gear has ", edgesNb, " edges")
Face_g_1_tr = geompy.MakeTranslationTwoPoints(Face_g_1, p0, pth)
id_face_g_1_tr = geompy.addToStudyInFather(Gear, Face_g_1_tr, "Face of Gear by four points, translated")
if isMeshTest == 1 and smesh is not None:
- print "##################### Build Mesh #####################"
+ print("##################### Build Mesh #####################")
# ---- add a middle block of spanner handle in study
Id_Edge1 = geompy.addToStudyInFather(FaceTop, Edge1, "Edge 1")
Id_Edge2 = geompy.addToStudyInFather(FaceTop, Edge2, "Edge 2")
- print "-------------------------- Algorithm and Hypothesis"
+ print("-------------------------- Algorithm and Hypothesis")
- print "---- Init a Mesh with the Spanner"
+ print("---- Init a Mesh with the Spanner")
mesh = smesh.Mesh(Spanner, "Meshed Spanner")
- print "-------------------------- add hypothesis to Spanner"
+ print("-------------------------- add hypothesis to Spanner")
- print "-------------------------- NumberOfSegments"
+ print("-------------------------- NumberOfSegments")
algoReg = mesh.Segment()
listHyp = algoReg.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
- print algoReg.GetName()
- print algoReg.GetId()
+ print(hyp)
+ print(algoReg.GetName())
+ print(algoReg.GetId())
algoReg.SetName("Regular_1D")
hypNbSeg3 = algoReg.NumberOfSegments(3)
- print hypNbSeg3.GetName()
- print hypNbSeg3.GetId()
- print hypNbSeg3.GetNumberOfSegments()
+ print(hypNbSeg3.GetName())
+ print(hypNbSeg3.GetId())
+ print(hypNbSeg3.GetNumberOfSegments())
smesh.SetName(hypNbSeg3, "NumberOfSegments_3")
- print "-------------------------- Quadrangle_2D"
+ print("-------------------------- Quadrangle_2D")
algoQuad = mesh.Quadrangle()
listHyp = algoQuad.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
- print algoQuad.GetName()
- print algoQuad.GetId()
+ print(hyp)
+ print(algoQuad.GetName())
+ print(algoQuad.GetId())
algoQuad.SetName("Quadrangle_2D")
- print "-------------------------- add hypothesis to the Middle Block"
+ print("-------------------------- add hypothesis to the Middle Block")
- print "-------------------------- LocalLength"
+ print("-------------------------- LocalLength")
algoRegMb = mesh.Segment(BlockMh)
hypLen1 = algoRegMb.LocalLength(10)
- print hypLen1.GetName()
- print hypLen1.GetId()
- print hypLen1.GetLength()
+ print(hypLen1.GetName())
+ print(hypLen1.GetId())
+ print(hypLen1.GetLength())
smesh.SetName(hypLen1, "Local_Length_10")
- print "-------------------------- add hypothesis to the long edges of the Top Face of the Middle Block"
+ print("-------------------------- add hypothesis to the long edges of the Top Face of the Middle Block")
algoRegE1 = mesh.Segment(Edge1)
hypPropE1 = algoRegE1.Propagation()
- print hypPropE1.GetName()
- print hypPropE1.GetId()
+ print(hypPropE1.GetName())
+ print(hypPropE1.GetId())
smesh.SetName(hypPropE1, "Propagation hypothesis")
smesh.SetName(algoRegE1.GetSubMesh(), "SubMesh Edge 1 of Top Face")
algoRegE2 = mesh.Segment(Edge2)
hypPropE2 = algoRegE2.Propagation()
- print hypPropE2.GetName()
- print hypPropE2.GetId()
+ print(hypPropE2.GetName())
+ print(hypPropE2.GetId())
smesh.SetName(hypPropE2, "Propagation hypothesis")
smesh.SetName(algoRegE2.GetSubMesh(), "SubMesh Edge 2 of Top Face")
- print "-------------------------- compute the mesh"
+ print("-------------------------- compute the mesh")
mesh.Compute()
- 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 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:")
+ 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())
return Spanner
sse_id = geompy.GetSubShapeID(Prism, sse)
if sse_id != eid:
- print "Error: GetSubShape() or GetSubShapeID() has failed!"
+ print("Error: GetSubShape() or GetSubShapeID() has failed!")
IDlist_e = []
IDlist_e.append(geompy.GetSubShapeID(Prism, prism_edges[0]))
Archimede = geompy.Archimede(Box, weight, waterdensity,
meshingdeflection) #(GEOM_Object, 3 Doubles)->GEOM_Object
mindist = geompy.MinDistanceComponents(TranslVect, Mirror) #(2 GEOM_Object)->4 Doubles
- print "Minumal distance between TranslVect and Mirror is", mindist[0],
- print "by components:", mindist[1], ",", mindist[2], ",", mindist[3]
+ print("Minumal distance between TranslVect and Mirror is", mindist[0], end=' ')
+ print("by components:", mindist[1], ",", mindist[2], ",", mindist[3])
CheckShape = geompy.CheckShape(Prism) #(GEOM_Object)->Boolean
- print "CheckShape(Prism) = ", CheckShape
+ print("CheckShape(Prism) = ", CheckShape)
#Partition objects
Partition = geompy.MakePartition([Box], [Plane]) #(2 Lists Of GEOM_Object)->GEOM_Object
# GetExistingSubObjects
SubObjsAll = geompy.GetExistingSubObjects(Box, True)
- print "For now, Box has the following created sub-objects:", SubObjsAll
+ print("For now, Box has the following created sub-objects:", SubObjsAll)
# GetGroups
SubGrpsAll = geompy.GetGroups(Box)
- print "For now, Box has the following created groups:", SubGrpsAll
+ print("For now, Box has the following created groups:", SubGrpsAll)
# SubShapeAll
SubEdgeList = geompy.SubShapeAll(SubFace, geompy.ShapeType["EDGE"])
# SubShapeAllIDs
SubEdgeIDsList = geompy.SubShapeAllIDs(SubFace, geompy.ShapeType["EDGE"])
- print "IDs of edges of SubFace:", SubEdgeIDsList, "(unsorted)"
+ print("IDs of edges of SubFace:", SubEdgeIDsList, "(unsorted)")
group = geompy.CreateGroup(SubFace, geompy.ShapeType["EDGE"])
geompy.UnionIDs(group, SubEdgeIDsList)
geompy.addToStudyInFather(SubFace, group, "Group of all edges")
# SubShapeAllSortedCentresIDs
SubEdgeIDsList = geompy.SubShapeAllSortedCentresIDs(SubFace, geompy.ShapeType["EDGE"])
- print "IDs of edges of SubFace:", SubEdgeIDsList, "(sorted)"
+ print("IDs of edges of SubFace:", SubEdgeIDsList, "(sorted)")
# GetSubShape and GetSubShapeID
for ind in SubEdgeIDsList:
edge = geompy.GetSubShape(SubFace, [ind])
ind_e = geompy.GetSubShapeID(SubFace, edge)
if ind_e != ind:
- print "Error in GetSubShape or GetSubShapeID"
+ print("Error in GetSubShape or GetSubShapeID")
# RestoreSubShapes
geompy.RestoreSubShapes(Copy)
geompy.MakeExtraction(Box, [16], "Ext_no_vertex")
- print "DONE"
+ print("DONE")
# WARNING: assure name uniquness to check geompy.GetField( shape, name )
try:
field = geompy.CreateField(shape, name, ftype, dimension, componentNames)
- except Exception, e:
+ except Exception as e:
if nbFiOrMustFail == MustFail:
- print "Ok, expected exception caught: %s"%e
+ print("Ok, expected exception caught: %s"%e)
return
raise e
if nbFiOrMustFail == MustFail:
- raise RuntimeError, "Expected exception NOT thrown"
+ raise RuntimeError("Expected exception NOT thrown")
assert field.getShape()
assert field.getShape().IsSame( shape )
assert field.getName() == name
def CheckStepManips(field, step, stamp, values, nbStepsOrMustFail, toRemove=False):
try:
stp = field.addStep(step, stamp, values)
- except Exception, e:
+ except Exception as e:
if nbStepsOrMustFail == MustFail:
- print "Ok, expected exception caught: %s"%e
+ print("Ok, expected exception caught: %s"%e)
return
raise e
if nbStepsOrMustFail == MustFail:
- raise RuntimeError, "Expected exception NOT thrown"
+ raise RuntimeError("Expected exception NOT thrown")
assert field.countSteps() == nbStepsOrMustFail
assert len( field.getSteps() ) == nbStepsOrMustFail
assert step in field.getSteps()
CheckStepManips( bfield, 2, -2, [1,0]*4, 1 )
# int field on 6 faces
ifield = geompy.CreateField(shape, "intF", GEOM.FDT_Int, 2, ["id","domain"])
- CheckStepManips( ifield, -1, -10, range(12), 1 )
- CheckStepManips( ifield, -2, -20, range(6)*2, 2 )
+ CheckStepManips( ifield, -1, -10, list(range(12)), 1 )
+ CheckStepManips( ifield, -2, -20, list(range(6))*2, 2 )
# double field on a solid
dfield = geompy.CreateField(shape, "dblS", GEOM.FDT_Double, 3, ["a","b","c"])
CheckStepManips( dfield, -1, -10, [-1.1, 2.3, 4000], 1 )
- CheckStepManips( dfield, -2, -20, range(3), 2 )
+ CheckStepManips( dfield, -2, -20, list(range(3)), 2 )
# assert exception in case of invalid parameters
CheckStepManips( sfield, -1, -10, ["25 Sep","2013"], MustFail ) # step already exists
# dump the study
import salome
assert( salome.myStudy.DumpStudy(os.path.dirname(dumpFile), os.path.basename(dumpFile), 1, 0))
- execfile( pyFile )
+ exec(compile(open( pyFile ).read(), pyFile, 'exec'))
os.remove( pyFile )
- print "Field manipulations work OK"
+ print("Field manipulations work OK")
theShape = geompy.MakePrismVecH(face, edge, 130)
#Check shape
- print "Before ProcessShape:"
+ print("Before ProcessShape:")
isValid = geompy.CheckShape(theShape)
if isValid == 0:
- print "The shape is not valid"
+ print("The shape is not valid")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
#Process Shape
Operators = ["FixShape"]
PS = geompy.ProcessShape(theShape, Operators, Parameters, Values)
#Check shape
- print "After ProcessShape:"
+ print("After ProcessShape:")
isValid = geompy.CheckShape(PS)
if isValid == 0:
- print "The shape is not valid"
- raise RuntimeError, "It seems, that the ProcessShape() has failed"
+ print("The shape is not valid")
+ raise RuntimeError("It seems, that the ProcessShape() has failed")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
#Add In Study
Id_Shape = geompy.addToStudy(theShape, "Invalid Shape")
nbw1 = nbw1 + 1
if nbw1 != 2:
- raise RuntimeError, "GetFreeBoundary(f12) must return 2 closed wires, but returned ", nbw1
+ raise RuntimeError("GetFreeBoundary(f12) must return 2 closed wires, but returned ").with_traceback(nbw1)
#SuppressInternalWires
face = geompy.SuppressInternalWires(f12, [])
nbw2 = nbw2 + 1
if nbw2 != 1:
- print "GetFreeBoundary(face) must return 1 closed wires, but returned ", nbw2
- raise RuntimeError, "SuppressInternalWires() works not correctly"
+ print("GetFreeBoundary(face) must return 1 closed wires, but returned ", nbw2)
+ raise RuntimeError("SuppressInternalWires() works not correctly")
#Add In Study
Id_face = geompy.addToStudy(face, "Face without internal wires")
Shape = geompy.MakePolyline([p0, pz, py, p200])
#Check shape
- print "Before closing contour:"
+ print("Before closing contour:")
isValid = geompy.CheckShape(Shape)
if isValid == 0:
- print "The shape is not valid"
+ print("The shape is not valid")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
#Close Contour
IsCommonVertex = 0 # false
CC = geompy.CloseContour(Shape, Wires, IsCommonVertex)
#Check shape
- print "After closing contour:"
+ print("After closing contour:")
isValid = geompy.CheckShape(CC)
if isValid == 0:
- print "The shape is not valid"
- raise RuntimeError, "It seems, that the contour was not closed"
+ print("The shape is not valid")
+ raise RuntimeError("It seems, that the contour was not closed")
else:
- print "The shape seems to be valid"
+ print("The shape seems to be valid")
#Add In Study
Id_Shape = geompy.addToStudy(Shape, "Shape with open wire")
f_id = geompy.addToStudyInFather(Cut, face, f_name)
f_glob_id = geompy.GetSubShapeID(Cut, face)
- print "face ", ind, " global index = ", f_glob_id
+ print("face ", ind, " global index = ", f_glob_id)
ind = ind + 1
f_glob_id_0 = geompy.GetSubShapeID(Cut, faces[0])
f_id = geompy.addToStudyInFather(cut_without_f_0, face, f_name)
f_glob_id = geompy.GetSubShapeID(cut_without_f_0, face)
- print "face ", ind, " global index = ", f_glob_id
+ print("face ", ind, " global index = ", f_glob_id)
ind = ind + 1
f_glob_id_3 = geompy.GetSubShapeID(cut_without_f_0, faces1[3])
w_id = geompy.addToStudyInFather(cut_without_f_0_3, wire, w_name)
w_glob_id = geompy.GetSubShapeID(cut_without_f_0_3, wire)
- print "wire ", ind, " global index = ", w_glob_id
+ print("wire ", ind, " global index = ", w_glob_id)
ind = ind + 1
w_3 = geompy.GetSubShapeID(cut_without_f_0_3, wires[3])
Coords = geompy.PointCoordinates(p137)
if Coords[0] != 10 or Coords[1] != 30 or Coords[2] != 70:
- print "Coordinates of p137 must be (10, 30, 70), but returned (", Coords[0], ", ", Coords[1], ", ", Coords[2], ")"
+ print("Coordinates of p137 must be (10, 30, 70), but returned (", Coords[0], ", ", Coords[1], ", ", Coords[2], ")")
####### CheckShape #######
(IsValid, err) = geompy.CheckShape(box, 0, 2)
if IsValid == 0:
geompy.PrintShapeError(box, err)
- raise RuntimeError, "Invalid box created"
+ raise RuntimeError("Invalid box created")
else:
- print "\nBox is valid"
+ print("\nBox is valid")
####### Detect Self-intersections #######
selfIntersected = geompy.MakeCompound([box, cylinder])
if geompy.CheckSelfIntersections(selfIntersected):
- raise RuntimeError, "Existing self-intersection is not detected"
+ raise RuntimeError("Existing self-intersection is not detected")
####### Detect Self-intersections fast #######
if salome_version.getXVersion() > "0x70600":
if geompy.CheckSelfIntersectionsFast(selfIntersected):
- raise RuntimeError, "Existing self-intersection is not detected"
+ raise RuntimeError("Existing self-intersection is not detected")
####### Fast intersection #######
if not geompy.FastIntersect(box, cylinder)[0]:
- raise RuntimeError, "Existing intersection is not detected"
+ raise RuntimeError("Existing intersection is not detected")
####### WhatIs #######
Descr = geompy.WhatIs(box)
- print "\nBox 10x30x70 description:"
- print Descr
+ print("\nBox 10x30x70 description:")
+ print(Descr)
####### NbShapes #######
NbSolids = geompy.NbShapes(box, geompy.ShapeType["SOLID"])
- print "\nBox 10x30x70 quantity of solids:", NbSolids
+ print("\nBox 10x30x70 quantity of solids:", NbSolids)
####### ShapeInfo #######
BoxInfo = geompy.ShapeInfo(box)
- print "\nBox 10x30x70 shapes:"
- print BoxInfo
+ print("\nBox 10x30x70 shapes:")
+ print(BoxInfo)
####### BasicProperties #######
Props = geompy.BasicProperties(box)
- print "\nBox 10x30x70 Basic Properties:"
- print " Wires length: ", Props[0]
- print " Surface area: ", Props[1]
- print " Volume : ", Props[2]
+ print("\nBox 10x30x70 Basic Properties:")
+ print(" Wires length: ", Props[0])
+ print(" Surface area: ", Props[1])
+ print(" Volume : ", Props[2])
dl = math.sqrt((Props[0] - 880)*(Props[0] - 880))
da = math.sqrt((Props[1] - 6200)*(Props[1] - 6200))
#print "|Props[0] - 880| = ", dl
if dl > 1e-7 or da > 1e-7 or dv > 1e-7:
- print "While must be:"
- print " Wires length: ", 880
- print " Surface area: ", 6200
- print " Volume : ", 21000
+ print("While must be:")
+ print(" Wires length: ", 880)
+ print(" Surface area: ", 6200)
+ print(" Volume : ", 21000)
####### BoundingBox #######
BB = geompy.BoundingBox(box)
- print "\nBounding Box of box 10x30x70:"
- print " Xmin = ", BB[0], ", Xmax = ", BB[1]
- print " Ymin = ", BB[2], ", Ymax = ", BB[3]
- print " Zmin = ", BB[4], ", Zmax = ", BB[5]
+ print("\nBounding Box of box 10x30x70:")
+ print(" Xmin = ", BB[0], ", Xmax = ", BB[1])
+ print(" Ymin = ", BB[2], ", Ymax = ", BB[3])
+ print(" Zmin = ", BB[4], ", Zmax = ", BB[5])
BB = geompy.MakeBoundingBox(box)
geompy.addToStudy(BB, "BoundingBox")
####### Inertia #######
In = geompy.Inertia(box)
- print "\nInertia matrix of box 10x30x70:"
- print " (", In[0], ", ", In[1], ", ", In[2], ")"
- print " (", In[3], ", ", In[4], ", ", In[5], ")"
- print " (", In[6], ", ", In[7], ", ", In[8], ")"
- print "Main moments of inertia of box 10x30x70:"
- print " Ix = ", In[9], ", Iy = ", In[10], ", Iz = ", In[11]
+ print("\nInertia matrix of box 10x30x70:")
+ print(" (", In[0], ", ", In[1], ", ", In[2], ")")
+ print(" (", In[3], ", ", In[4], ", ", In[5], ")")
+ print(" (", In[6], ", ", In[7], ", ", In[8], ")")
+ print("Main moments of inertia of box 10x30x70:")
+ print(" Ix = ", In[9], ", Iy = ", In[10], ", Iz = ", In[11])
####### Tolerance #######
Toler = geompy.Tolerance(box)
- print "\nBox 10x30x70 tolerance:"
- print " Face min. tolerance: ", Toler[0]
- print " Face max. tolerance: ", Toler[1]
- print " Edge min. tolerance: ", Toler[2]
- print " Edge max. tolerance: ", Toler[3]
- print " Vertex min. tolerance: ", Toler[4]
- print " Vertex max. tolerance: ", Toler[5]
+ print("\nBox 10x30x70 tolerance:")
+ print(" Face min. tolerance: ", Toler[0])
+ print(" Face max. tolerance: ", Toler[1])
+ print(" Edge min. tolerance: ", Toler[2])
+ print(" Edge max. tolerance: ", Toler[3])
+ print(" Vertex min. tolerance: ", Toler[4])
+ print(" Vertex max. tolerance: ", Toler[5])
####### MakeCDG #######
pcdg = geompy.MakeCDG(box)
if pcdg is None:
- raise RuntimeError, "MakeCDG(box) failed"
+ raise RuntimeError("MakeCDG(box) failed")
else:
- print "\nCentre of gravity of box has been successfully obtained:"
+ print("\nCentre of gravity of box has been successfully obtained:")
Coords = geompy.PointCoordinates(pcdg)
- print "(", Coords[0], ", ", Coords[1], ", ", Coords[2], ")"
+ print("(", Coords[0], ", ", Coords[1], ", ", Coords[2], ")")
if Coords[0] != 5 or Coords[1] != 15 or Coords[2] != 35:
- print "But must be (5, 15, 35)"
+ print("But must be (5, 15, 35)")
####### GetNormal #######
face0 = faces[0]
vnorm = geompy.GetNormal(face0)
if vnorm is None:
- raise RuntimeError, "GetNormal(face0) failed"
+ raise RuntimeError("GetNormal(face0) failed")
else:
geompy.addToStudy(face0, "Face0")
geompy.addToStudy(vnorm, "Normale to Face0")
- print "\nNormale of face has been successfully obtained:"
+ print("\nNormale of face has been successfully obtained:")
#Coords = geompy.PointCoordinates(pcdg)
#print "(", Coords[0], ", ", Coords[1], ", ", Coords[2], ")"
#if Coords[0] != 5 or Coords[1] != 15 or Coords[2] != 35:
#print " On Box (", MinDist[1], ", ", MinDist[2], ", ", MinDist[3], ")"
#print " On Cube (", MinDist[4], ", ", MinDist[5], ", ", MinDist[6], ")"
- print "\nMinimal distance between Box and Cube = ", MinDist
+ print("\nMinimal distance between Box and Cube = ", MinDist)
MinDistComps = geompy.MinDistanceComponents(box, cube)
- print "\nMinimal distance between Box and Cube = ", MinDistComps[0]
- print "Its components are (", MinDistComps[1], ", ", MinDistComps[2], ", ", MinDistComps[3], ")"
+ print("\nMinimal distance between Box and Cube = ", MinDistComps[0])
+ print("Its components are (", MinDistComps[1], ", ", MinDistComps[2], ", ", MinDistComps[3], ")")
# Get all closest points
[nbSols, listCoords] = geompy.ClosestPoints(box, cube)
# in one plane
Angle = geompy.GetAngle(OX, OXY)
- print "\nAngle between OX and OXY = ", Angle
+ print("\nAngle between OX and OXY = ", Angle)
if math.fabs(Angle - 45.0) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 45.0"
+ print(" Error: returned angle is", Angle, "while must be 45.0")
Angle = geompy.GetAngleRadians(OX, OXY)
- print "\nAngle between OX and OXY in radians = ", Angle
+ print("\nAngle between OX and OXY in radians = ", Angle)
if math.fabs(Angle - math.pi/4) > 1e-05:
- print " Error: returned angle is", Angle, "while must be pi/4"
+ print(" Error: returned angle is", Angle, "while must be pi/4")
pass
# not in one plane
OXY_shift = geompy.MakeTranslation(OXY,10,-10,20)
Angle = geompy.GetAngle(OX, OXY_shift)
- print "Angle between OX and OXY_shift = ", Angle
+ print("Angle between OX and OXY_shift = ", Angle)
if math.fabs(Angle - 45.0) > 1e-05:
- print " Error: returned angle is", Angle, "while must be 45.0"
+ print(" Error: returned angle is", Angle, "while must be 45.0")
####### Position (LCS) #######
Pos = geompy.GetPosition(box)
- print "\nPosition(LCS) of box 10x30x70:"
- print "Origin: (", Pos[0], ", ", Pos[1], ", ", Pos[2], ")"
- print "Z axis: (", Pos[3], ", ", Pos[4], ", ", Pos[5], ")"
- print "X axis: (", Pos[6], ", ", Pos[7], ", ", Pos[8], ")"
+ print("\nPosition(LCS) of box 10x30x70:")
+ print("Origin: (", Pos[0], ", ", Pos[1], ", ", Pos[2], ")")
+ print("Z axis: (", Pos[3], ", ", Pos[4], ", ", Pos[5], ")")
+ print("X axis: (", Pos[6], ", ", Pos[7], ", ", Pos[8], ")")
####### KindOfShape #######
Kind = geompy.KindOfShape(box)
- print "\nKindOfShape(box 10x30x70):", Kind
+ print("\nKindOfShape(box 10x30x70):", Kind)
#if Kind[0] != geompy.kind.BOX:
# print "Error: returned type is", Kind[0], "while must be", geompy.kind.BOX
Kind = geompy.KindOfShape(p137)
- print "\nKindOfShape(p137):", Kind
+ print("\nKindOfShape(p137):", Kind)
if Kind[0] != geompy.kind.VERTEX:
- print " Error: returned type is", Kind[0], "while must be", geompy.kind.VERTEX
+ print(" Error: returned type is", Kind[0], "while must be", geompy.kind.VERTEX)
else:
dx = math.fabs(Kind[1] - 10)
dy = math.fabs(Kind[2] - 30)
dz = math.fabs(Kind[3] - 70)
if (dx + dy + dz) > 1e-5:
- print " Error: coordinates are (", Kind[1], ",", Kind[2], ",", Kind[3], ") while must be (10, 20, 30)"
+ print(" Error: coordinates are (", Kind[1], ",", Kind[2], ",", Kind[3], ") while must be (10, 20, 30)")
pass
def TestExportImport (geompy, shape):
- print "Test Export/Import ...",
+ print("Test Export/Import ...", end=' ')
tmpDir = os.getenv("TEMP")
if tmpDir == None:
aNewShape = geompy.RestoreShape(aStream)
geompy.addToStudy(aNewShape, "aNewShape")
- print "OK"
+ print("OK")
def TestOtherOperations (geompy, math):
# NumberOf
NumberOfFaces = geompy.NumberOfFaces(Box)
if NumberOfFaces != 6:
- print "Bad number of faces in BOX!"
+ print("Bad number of faces in BOX!")
NumberOfEdges = geompy.NumberOfEdges(Box)
if NumberOfEdges != 12:
- print "Bad number of edges in BOX!"
+ print("Bad number of edges in BOX!")
NumberOfSolids = geompy.NumberOfSolids(Box)
if NumberOfSolids != 1:
- print "Bad number of solids in BOX!"
+ print("Bad number of solids in BOX!")
NumberOfShapes = geompy.NumberOfSubShapes(Box, geompy.ShapeType["SHAPE"])
if NumberOfShapes != 34:
- print "Bad number of shapes in BOX!"
+ print("Bad number of shapes in BOX!")
# MakeBlockExplode
Compound = geompy.MakeCompound([Box, Sphere])
IsValid = geompy.CheckCompoundOfBlocks(Compound1)
if IsValid == 0:
- print "The Blocks Compound is NOT VALID"
+ print("The Blocks Compound is NOT VALID")
(NonBlocks, NonQuads) = geompy.GetNonBlocks(Compound1)
if NonBlocks is not None:
geompy.addToStudyInFather(Compound1, NonBlocks, "Group of non-hexahedral solids")
if NonQuads is not None:
geompy.addToStudyInFather(Compound1, NonQuads, "Group of non-quadrangular faces")
else:
- print "The Blocks Compound is VALID"
+ print("The Blocks Compound is VALID")
IsValid = geompy.CheckCompoundOfBlocks(Box)
if IsValid == 0:
- print "The Box is NOT VALID"
+ print("The Box is NOT VALID")
else:
- print "The Box is VALID"
+ print("The Box is VALID")
# GetSame
Cone_ss = geompy.GetSame(Compound1, Cone)
# GetObjectIDs
GetObjectIDs = geompy.GetObjectIDs(CreateGroup)
- print "Group of Box's faces includes the following IDs:"
- print "(must be ", f_ind_6, ", ", f_ind_3, " and ", f_ind_5, ")"
+ print("Group of Box's faces includes the following IDs:")
+ print("(must be ", f_ind_6, ", ", f_ind_3, " and ", f_ind_5, ")")
for ObjectID in GetObjectIDs:
- print " ", ObjectID
+ print(" ", ObjectID)
# GetMainShape
BoxCopy = geompy.GetMainShape(CreateGroup)
# Check
GetObjectIDs = geompy.GetObjectIDs(CreateGroup)
- print "Group of Box's faces includes the following IDs:"
- print "(must be ", f_ind_6, ", ", f_ind_1, " and ", f_ind_2, ")"
+ print("Group of Box's faces includes the following IDs:")
+ print("(must be ", f_ind_6, ", ", f_ind_1, " and ", f_ind_2, ")")
for ObjectID in GetObjectIDs:
- print " ", ObjectID
+ print(" ", ObjectID)
# Boolean Operations on Groups (Union, Intersection, Cut)
Group_1 = geompy.CreateGroup(Box, geompy.ShapeType["FACE"])
'4':"FACE", '5':"WIRE", '6':"EDGE", '7':"VERTEX", '8':"SHAPE"}
GroupType = geompy.GetType(CreateGroup)
- print "Type of elements of the created group is ", ShapeTypeString[`GroupType`]
+ print("Type of elements of the created group is ", ShapeTypeString[repr(GroupType)])
# Prepare data for the following operations
p0 = geompy.MakeVertex(0, 0, 0)
geompy.ShapeType["FACE"])
ind = 1
for shFace in sharedFaces:
- geompy.addToStudy(shFace, "sharedFace_" + `ind`)
+ geompy.addToStudy(shFace, "sharedFace_" + repr(ind))
ind = ind + 1
pass
geompy.ShapeType["EDGE"])
ind = 1
for shEdge in sharedEdges:
- geompy.addToStudy(shEdge, "sharedEdge_" + `ind`)
+ geompy.addToStudy(shEdge, "sharedEdge_" + repr(ind))
ind = ind + 1
pass
comp = geompy.MakeCompound(edges_onin_quad)
geompy.addToStudy(comp, "Edges of F12 ONIN Quadrangle")
if len( edges_onin_quad ) != 4:
- print "Error in GetShapesOnQuadrangle()"
+ print("Error in GetShapesOnQuadrangle()")
# GetShapesOnQuadrangleIDs
vertices_on_quad_ids = geompy.GetShapesOnQuadrangleIDs(f12, geompy.ShapeType["VERTEX"],
comp = geompy.MakeCompound(edges_on_box)
geompy.addToStudy(comp, "Edges of part ON box b0")
if len( edges_on_box ) != 12:
- print "Error in GetShapesOnBox()"
+ print("Error in GetShapesOnBox()")
# GetShapesOnBoxIDs
faces_on_box_ids = geompy.GetShapesOnBoxIDs(b0, part, geompy.ShapeType["FACE"],
comp = geompy.MakeCompound(faces_in_sh)
geompy.addToStudy(comp, "Faces of part IN shape sh_1")
if len(faces_in_sh) != 11:
- print "Error in GetShapesOnShape()"
+ print("Error in GetShapesOnShape()")
# GetShapesOnShapeAsCompound
faces_in_sh_c = geompy.GetShapesOnShapeAsCompound(sh_1, part, geompy.ShapeType["FACE"],
geompy.UnionIDs(edges_in_sh, edges_in_sh_ids)
geompy.addToStudyInFather(part, edges_in_sh, "Group of edges in shape sh_1")
if len(edges_in_sh_ids) != 15:
- print "Error in GetShapesOnShapeIDs()"
+ print("Error in GetShapesOnShapeIDs()")
# Prepare arguments for GetInPlace and GetInPlaceByHistory
box5 = geompy.MakeBoxDXDYDZ(100, 100, 100)
box6_faces = geompy.SubShapeAll(box6, geompy.ShapeType["FACE"])
for ifa in range(6):
- geompy.addToStudyInFather(box5, box5_faces[ifa], "Face" + `ifa + 1`)
- geompy.addToStudyInFather(box6, box6_faces[ifa], "Face" + `ifa + 1`)
+ geompy.addToStudyInFather(box5, box5_faces[ifa], "Face" + repr(ifa + 1))
+ geompy.addToStudyInFather(box6, box6_faces[ifa], "Face" + repr(ifa + 1))
# GetInPlace(theShapeWhere, theShapeWhat)
ibb = 5
# there is no reflection in the result.
if refl_box_face is not None:
error = "Result of GetInPlace must be NULL for face "
- error += `ifa` + " of box " + `ibb`
- raise RuntimeError, error
+ error += repr(ifa) + " of box " + repr(ibb)
+ raise RuntimeError(error)
else:
- ssname = "Reflection of face " + `ifa` + " of box " + `ibb`
+ ssname = "Reflection of face " + repr(ifa) + " of box " + repr(ibb)
geompy.addToStudyInFather(part, refl_box_face, ssname)
ifa = ifa + 1
ibb = ibb + 1
for afaces in faces_list:
ifa = 1
for aface in afaces:
- ssname = "Reflection of face " + `ifa` + " of box " + `ibb` + " (by history)"
+ ssname = "Reflection of face " + repr(ifa) + " of box " + repr(ibb) + " (by history)"
if ibb == 6 and (ifa == 2 or ifa == 4):
# use IDL interface directly to avoid error message appearence in Python console
refl_box_face = geompy.ShapesOp.GetInPlaceByHistory(part, aface)
if refl_box_face is not None:
geompy.addToStudyInFather(part, refl_box_face, ssname)
error = "Result of GetInPlaceByHistory must be NULL for face "
- error += `ifa` + " of box " + `ibb`
- raise RuntimeError, error
+ error += repr(ifa) + " of box " + repr(ibb)
+ raise RuntimeError(error)
else:
# use geompy interface
refl_box_face = geompy.GetInPlaceByHistory(part, aface)
geompy = geomBuilder.New(salome.myStudy)
import math
-import GEOM_Spanner
+from . import GEOM_Spanner
isBlocksTest = 0 # False
isMeshTest = 0 # False
x2 = 10. * (ind+1)
y2 = 20. * (ind+1)
z2 = 30. * (ind+1)
- print x1, y1, z1, x2, y2, z2
+ print(x1, y1, z1, x2, y2, z2)
point1 = geompy.MakeVertex(x1, y1, z1)
name1 = "point1_%d"%(ind)
y3 = 0. * (ind+1)
z3 = -10. * (ind+1)
- print x1, y1, z1, x2, y2, z2, x3, y3, z3
+ print(x1, y1, z1, x2, y2, z2, x3, y3, z3)
point1 = geompy.MakeVertex(x1, y1, z1)
name1 = "point1_%d"%(ind)
from launchConfigureParser import verbose
-if verbose(): print "============== import GEOM ======================="
+if verbose(): print("============== import GEOM =======================")
import GEOM
import math
-import GEOM_TestAll
-import GEOM_TestOthers
-import GEOM_TestHealing
-import GEOM_TestMeasures
-import GEOM_TestField
+from . import GEOM_TestAll
+from . import GEOM_TestOthers
+from . import GEOM_TestHealing
+from . import GEOM_TestMeasures
+from . import GEOM_TestField
GEOM_TestField.TestField(geompy, math) # it goes 1st as it checks Python Dump
GEOM_TestMeasures.TestMeasureOperations(geompy, math)
anOp = GetIGESPluginOperations(self)
anOp.ExportIGES(theObject, theFileName, theVersion)
if anOp.IsDone() == 0:
- raise RuntimeError, "Export : " + anOp.GetErrorCode()
+ raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
anIsIgnoreUnits = theIsIgnoreUnits
aName = theName
- if isinstance( theIsIgnoreUnits, basestring ):
+ if isinstance( theIsIgnoreUnits, str ):
anIsIgnoreUnits = False
aName = theIsIgnoreUnits
pass
os.remove(theFilenameToSave)
salome.myStudyManager.SaveAs(theFilenameToSave, salome.myStudy, 0)
else:
- print "You have no enough permissions to overwrite HDF file: ",theFilenameToSave
+ print("You have no enough permissions to overwrite HDF file: ",theFilenameToSave)
else:
salome.myStudyManager.SaveAs(theFilenameToSave, salome.myStudy, 0)
anOp = GetSTEPPluginOperations(self)
anOp.ExportSTEP(theObject, theFileName, theUnit)
if anOp.IsDone() == 0:
- raise RuntimeError, "Export : " + anOp.GetErrorCode()
+ raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
anIsIgnoreUnits = theIsIgnoreUnits
anIsCreateAssemblies = IsCreateAssemblies;
aName = theName
- if isinstance( theIsIgnoreUnits, basestring ):
+ if isinstance( theIsIgnoreUnits, str ):
anIsIgnoreUnits = False
aName = theIsIgnoreUnits
pass
- elif isinstance( IsCreateAssemblies, basestring ):
+ elif isinstance( IsCreateAssemblies, str ):
anIsCreateAssemblies = False
aName = IsCreateAssemblies
pass
anOp = GetSTLPluginOperations(self)
anOp.ExportSTL(theObject, theFileName, theIsASCII, theDeflection, theIsRelative )
if anOp.IsDone() == 0:
- raise RuntimeError, "Export : " + anOp.GetErrorCode()
+ raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
anOp = GetVTKPluginOperations(self)
anOp.ExportVTK(theObject, theFileName, theDeflection)
if anOp.IsDone() == 0:
- raise RuntimeError, "Export : " + anOp.GetErrorCode()
+ raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
def _toListOfNames(_names, _size=-1):
l = []
import types
- if type(_names) in [types.ListType, types.TupleType]:
+ if type(_names) in [list, tuple]:
for i in _names: l.append(i)
elif _names:
l.append(_names)
## @ingroup l1_geomBuilder_auxiliary
def RaiseIfFailed (Method_name, Operation):
if not Operation.IsDone() and Operation.GetErrorCode() != "NOT_FOUND_ANY":
- raise RuntimeError, Method_name + " : " + Operation.GetErrorCode()
+ raise RuntimeError(Method_name + " : " + Operation.GetErrorCode())
## Return list of variables value from salome notebook
## @ingroup l1_geomBuilder_auxiliary
if notebook.isVariable(parameter):
Result.append(notebook.get(parameter))
else:
- raise RuntimeError, "Variable with name '" + parameter + "' doesn't exist!!!"
+ raise RuntimeError("Variable with name '" + parameter + "' doesn't exist!!!")
pass
else:
Result.append(parameter)
Result = Result + str(notebook.get(parameter)) + " "
pass
else:
- raise RuntimeError, "Variable with name '" + parameter + "' doesn't exist!!!"
+ raise RuntimeError("Variable with name '" + parameter + "' doesn't exist!!!")
pass
pass
else:
# ---
def _item_name(_names, _defname, _idx=-1):
if not _names: _names = _defname
- if type(_names) in [types.ListType, types.TupleType]:
+ if type(_names) in [list, tuple]:
if _idx >= 0:
if _idx >= len(_names) or not _names[_idx]:
- if type(_defname) not in [types.ListType, types.TupleType]:
+ if type(_defname) not in [list, tuple]:
_name = "%s_%d"%(_defname, _idx+1)
elif len(_defname) > 0 and _idx >= 0 and _idx < len(_defname):
_name = _defname[_idx]
if not theName and not theDefaultName:
return # neither theName nor theDefaultName is given
import types
- if type(theObj) in [types.ListType, types.TupleType]:
+ if type(theObj) in [list, tuple]:
# list of objects is being published
idx = 0
for obj in theObj:
self.RestoreSubShapesSO(self.myStudy, aSObject, theArgs,
theFindMethod, theInheritFirstArg, True )
except:
- print "addToStudy() failed"
+ print("addToStudy() failed")
return ""
return aShape.GetStudyEntry()
aSObject = self.AddInStudy(self.myStudy, aShape, aName, aFather)
if aSObject and aName: aSObject.SetAttrString("AttributeName", aName)
except:
- print "addToStudyInFather() failed"
+ print("addToStudyInFather() failed")
return ""
return aShape.GetStudyEntry()
if isinstance(theA,str):
flag = True
theR,theH,theA,Parameters = ParseParameters(theR, theH, theA)
- if flag:
+ if flag:
theA = theA*math.pi/180.
- if theA<=0. or theA>=2*math.pi:
- raise ValueError("The angle parameter should be strictly between 0 and 2*pi.")
- anObj = self.PrimOp.MakeCylinderPntVecRHA(thePnt, theAxis, theR, theH, theA)
- RaiseIfFailed("MakeCylinderPntVecRHA", self.PrimOp)
- anObj.SetParameters(Parameters)
- self._autoPublish(anObj, theName, "cylinder")
+ if theA<=0. or theA>=2*math.pi:
+ raise ValueError("The angle parameter should be strictly between 0 and 2*pi.")
+ anObj = self.PrimOp.MakeCylinderPntVecRHA(thePnt, theAxis, theR, theH, theA)
+ RaiseIfFailed("MakeCylinderPntVecRHA", self.PrimOp)
+ anObj.SetParameters(Parameters)
+ self._autoPublish(anObj, theName, "cylinder")
return anObj
## Create a cylinder with given radius and height at
if flag:
theA = theA*math.pi/180.
if theA<=0. or theA>=2*math.pi:
- raise ValueError("The angle parameter should be strictly between 0 and 2*pi.")
+ raise ValueError("The angle parameter should be strictly between 0 and 2*pi.")
anObj = self.PrimOp.MakeCylinderRHA(theR, theH, theA)
RaiseIfFailed("MakeCylinderRHA", self.PrimOp)
anObj.SetParameters(Parameters)
theWithContact, theWithCorrection,
IsGenerateGroups)
if self.PrimOp.IsDone() == 0:
- print "Problems with pipe creation between ",i," and ",i+1," sections"
+ print("Problems with pipe creation between ",i," and ",i+1," sections")
RaiseIfFailed("MakePipeWithShellSections", self.PrimOp)
break
else:
- print "Pipe between ",i," and ",i+1," sections is OK"
+ print("Pipe between ",i," and ",i+1," sections is OK")
res.append(aList[0])
pass
pass
# Example: see GEOM_TestAll.py
anObj = self.ShapesOp.MakeFace(theWire, isPlanarWanted)
if isPlanarWanted and anObj is not None and self.ShapesOp.GetErrorCode() == "MAKE_FACE_TOLERANCE_TOO_BIG":
- print "WARNING: Cannot build a planar face: required tolerance is too big. Non-planar face is built."
+ print("WARNING: Cannot build a planar face: required tolerance is too big. Non-planar face is built.")
else:
RaiseIfFailed("MakeFace", self.ShapesOp)
self._autoPublish(anObj, theName, "face")
# Example: see GEOM_TestAll.py
anObj = self.ShapesOp.MakeFaceWires(ToList(theWires), isPlanarWanted)
if isPlanarWanted and anObj is not None and self.ShapesOp.GetErrorCode() == "MAKE_FACE_TOLERANCE_TOO_BIG":
- print "WARNING: Cannot build a planar face: required tolerance is too big. Non-planar face is built."
+ print("WARNING: Cannot build a planar face: required tolerance is too big. Non-planar face is built.")
else:
RaiseIfFailed("MakeFaceWires", self.ShapesOp)
self._autoPublish(anObj, theName, "face")
#if len(descr) > 0:
# raise RuntimeError, "MakeSolidShells : " + descr
if descr == "WRN_SHAPE_UNCLOSED":
- raise RuntimeError, "MakeSolidShells : Unable to create solid from unclosed shape"
+ raise RuntimeError("MakeSolidShells : Unable to create solid from unclosed shape")
anObj = self.ShapesOp.MakeSolidShells(theShells)
RaiseIfFailed("MakeSolidShells", self.ShapesOp)
self._autoPublish(anObj, theName, "solid")
theTolerance,Parameters = ParseParameters(theTolerance)
anObj = self.ShapesOp.MakeGlueFaces(ToList(theShapes), theTolerance, doKeepNonSolids)
if anObj is None:
- raise RuntimeError, "MakeGlueFaces : " + self.ShapesOp.GetErrorCode()
+ raise RuntimeError("MakeGlueFaces : " + self.ShapesOp.GetErrorCode())
anObj.SetParameters(Parameters)
self._autoPublish(anObj, theName, "glueFaces")
return anObj
anObj = self.ShapesOp.MakeGlueFacesByList(ToList(theShapes), theTolerance, ToList(theFaces),
doKeepNonSolids, doGlueAllEdges)
if anObj is None:
- raise RuntimeError, "MakeGlueFacesByList : " + self.ShapesOp.GetErrorCode()
+ raise RuntimeError("MakeGlueFacesByList : " + self.ShapesOp.GetErrorCode())
self._autoPublish(anObj, theName, "glueFaces")
return anObj
theTolerance,Parameters = ParseParameters(theTolerance)
anObj = self.ShapesOp.MakeGlueEdges(ToList(theShapes), theTolerance)
if anObj is None:
- raise RuntimeError, "MakeGlueEdges : " + self.ShapesOp.GetErrorCode()
+ raise RuntimeError("MakeGlueEdges : " + self.ShapesOp.GetErrorCode())
anObj.SetParameters(Parameters)
self._autoPublish(anObj, theName, "glueEdges")
return anObj
"""
anObj = self.ShapesOp.MakeGlueEdgesByList(ToList(theShapes), theTolerance, theEdges)
if anObj is None:
- raise RuntimeError, "MakeGlueEdgesByList : " + self.ShapesOp.GetErrorCode()
+ raise RuntimeError("MakeGlueEdgesByList : " + self.ShapesOp.GetErrorCode())
self._autoPublish(anObj, theName, "glueEdges")
return anObj
"""
Deprecated method. Use MultiRotate1DNbTimes instead.
"""
- print "The method MultiRotate1D is DEPRECATED. Use MultiRotate1DNbTimes instead."
+ print("The method MultiRotate1D is DEPRECATED. Use MultiRotate1DNbTimes instead.")
return self.MultiRotate1DNbTimes(theObject, theAxis, theNbTimes, theName)
## The same, as MultiRotate2DByStep(), but theAngle is in degrees.
Example of usage:
rot2d = geompy.MultiRotate2D(prism, vect, 60, 4, 50, 5)
"""
- print "The method MultiRotate2D is DEPRECATED. Use MultiRotate2DByStep instead."
+ print("The method MultiRotate2D is DEPRECATED. Use MultiRotate2DByStep instead.")
theAngle, theNbTimes1, theStep, theNbTimes2, Parameters = ParseParameters(theAngle, theNbTimes1, theStep, theNbTimes2)
anObj = self.TrsfOp.MultiRotate2D(theObject, theAxis, theAngle, theNbTimes1, theStep, theNbTimes2)
RaiseIfFailed("MultiRotate2D", self.TrsfOp)
vy = geompy.MakeVectorDXDYDZ(0, 100, 0)
MultiRot1D = geompy.MakeMultiRotation1D(prism, vy, pz, 6)
"""
- print "The method MakeMultiRotation1D is DEPRECATED. Use MakeMultiRotation1DNbTimes instead."
+ print("The method MakeMultiRotation1D is DEPRECATED. Use MakeMultiRotation1DNbTimes instead.")
aVec = self.MakeLine(aPoint,aDir)
# note: auto-publishing is done in self.MultiRotate1D()
anObj = self.MultiRotate1D(aShape, aVec, aNbTimes, theName)
vy = geompy.MakeVectorDXDYDZ(0, 100, 0)
MultiRot2D = geompy.MakeMultiRotation2D(f12, vy, pz, 45, 6, 30, 3)
"""
- print "The method MakeMultiRotation2D is DEPRECATED. Use MakeMultiRotation2DByStep instead."
+ print("The method MakeMultiRotation2D is DEPRECATED. Use MakeMultiRotation2DByStep instead.")
aVec = self.MakeLine(aPoint,aDir)
# note: auto-publishing is done in self.MultiRotate2D()
anObj = self.MultiRotate2D(aShape, aVec, anAngle, nbtimes1, aStep, nbtimes2, theName)
Descr = self.MeasuOp.PrintShapeErrors(theShape, theShapeErrors)
if theReturnStatus == 1:
return Descr
- print Descr
+ print(Descr)
pass
## Check a topology of the given shape.
if IsValid == 0:
if theReturnStatus == 0:
Descr = self.MeasuOp.PrintShapeErrors(theShape, ShapeErrors)
- print Descr
+ print(Descr)
if theReturnStatus == 1:
Descr = self.MeasuOp.PrintShapeErrors(theShape, ShapeErrors)
return (IsValid, Descr)
material groups are not automatically published.
"""
# Example: see GEOM_TestOthers.py
- print """
+ print("""
WARNING: Function ImportFile is deprecated, use Import<FormatName> instead,
where <FormatName> is a name of desirable format for importing.
- """
+ """)
aListObj = self.InsertOp.ImportFile(theFileName, theFormatName)
RaiseIfFailed("ImportFile", self.InsertOp)
aNbObj = len(aListObj)
if not theStream:
# this is the workaround to ignore invalid case when data stream is empty
if int(os.getenv("GEOM_IGNORE_RESTORE_SHAPE", "0")) > 0:
- print "WARNING: Result of RestoreShape is a NULL shape!"
+ print("WARNING: Result of RestoreShape is a NULL shape!")
return None
anObj = self.InsertOp.RestoreShape(theStream)
RaiseIfFailed("RestoreShape", self.InsertOp)
geompy.InsertOp.ExportTranslators()[0] method.
"""
# Example: see GEOM_TestOthers.py
- print """
+ print("""
WARNING: Function Export is deprecated, use Export<FormatName> instead,
where <FormatName> is a name of desirable format for exporting.
- """
+ """)
self.InsertOp.Export(theObject, theFileName, theFormatName)
if self.InsertOp.IsDone() == 0:
- raise RuntimeError, "Export : " + self.InsertOp.GetErrorCode()
+ raise RuntimeError("Export : " + self.InsertOp.GetErrorCode())
pass
pass
RaiseIfFailed("CheckCompoundOfBlocks", self.BlocksOp)
if IsValid == 0:
Descr = self.BlocksOp.PrintBCErrors(theCompound, BCErrors)
- print Descr
+ print(Descr)
return IsValid
## Retrieve all non blocks solids and faces from \a theShape.
edges_in_range.append(edge)
if len(edges_in_range) <= 0:
- print "No edges found by given criteria"
+ print("No edges found by given criteria")
return None
# note: auto-publishing is done in self.CreateGroup()
"""
nb_selected = sg.SelectedCount()
if nb_selected < 1:
- print "Select a shape before calling this function, please."
+ print("Select a shape before calling this function, please.")
return 0
if nb_selected > 1:
- print "Only one shape must be selected"
+ print("Only one shape must be selected")
return 0
id_shape = sg.getSelected(0)
if include_min: left_str = " <= "
if include_max: right_str = " <= "
- self.addToStudyInFather(shape, group_edges, "Group of edges with " + `min_length`
- + left_str + "length" + right_str + `max_length`)
+ self.addToStudyInFather(shape, group_edges, "Group of edges with " + repr(min_length)
+ + left_str + "length" + right_str + repr(max_length))
sg.updateObjBrowser(True)
"""
if isinstance( type, int ):
if type < 0 or type > 3:
- raise RuntimeError, "CreateField : Error: data type must be within [0-3] range"
+ raise RuntimeError("CreateField : Error: data type must be within [0-3] range")
type = [GEOM.FDT_Bool,GEOM.FDT_Int,GEOM.FDT_Double,GEOM.FDT_String][type]
f = self.FieldOp.CreateField( shape, name, type, dimension, componentNames)
elif isinstance( field, geomField ):
geom.RemoveObject( field.field )
else:
- raise RuntimeError, "RemoveField() : the object is not a field"
+ raise RuntimeError("RemoveField() : the object is not a field")
return
## Returns number of fields on a shape
"Adds a time step to the field"
stp = self.field.AddStep( self, step, stamp )
if not stp:
- raise RuntimeError, \
- "Field.addStep() : Error: step %s already exists in this field"%step
+ raise RuntimeError("Field.addStep() : Error: step %s already exists in this field"%step)
global geom
geom._autoPublish( stp, "", "Step %s, %s"%(step,stamp))
self.setValues( step, values )
"Returns a time step by its ID"
stp = self.field.GetStep(self, step)
if not stp:
- raise RuntimeError, "Step %s is missing from this field"%step
+ raise RuntimeError("Step %s is missing from this field"%step)
return stp
## Returns the time of the field step
errBeg = "Field.setValues(values) : Error: "
try:
ok = stp.SetValues( values )
- except Exception, e:
+ except Exception as e:
excStr = str(e)
if excStr.find("WrongPythonType") > 0:
- raise RuntimeError, errBeg +\
- "wrong type of values, %s values are expected"%str(self.getTypeEnum())[4:]
- raise RuntimeError, errBeg + str(e)
+ raise RuntimeError(errBeg +\
+ "wrong type of values, %s values are expected"%str(self.getTypeEnum())[4:])
+ raise RuntimeError(errBeg + str(e))
if not ok:
nbOK = self.field.GetArraySize(self)
nbKO = len(values)
if nbOK != nbKO:
- raise RuntimeError, errBeg + "len(values) must be %s but not %s"%(nbOK,nbKO)
+ raise RuntimeError(errBeg + "len(values) must be %s but not %s"%(nbOK,nbKO))
else:
- raise RuntimeError, errBeg + "failed"
+ raise RuntimeError(errBeg + "failed")
return
pass # end of class geomField
plugins = None
if plugins_var is not None:
plugins = plugins_var.split( ":" )
- plugins=filter(lambda x: len(x)>0, plugins)
+ plugins=[x for x in plugins if len(x)>0]
if plugins is not None:
for pluginName in plugins:
pluginBuilderName = pluginName + "Builder"
try:
exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
- except Exception, e:
+ except Exception as e:
from salome_utils import verbose
- print "Exception while loading %s: %s" % ( pluginBuilderName, e )
+ print("Exception while loading %s: %s" % ( pluginBuilderName, e ))
continue
exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
plugin = eval( pluginBuilderName )
# export the methods of geomBuilder
for k in dir( geom ):
- if k[0] == '_': continue
- globals()[k] = getattr( geom, k )
+ if k[0] == '_': continue
+ globals()[k] = getattr( geom, k )
pass
del k
ShapeType = geom.ShapeType
kind = geom.kind
pass
except:
- print "exception in geompy.py"
+ print("exception in geompy.py")
geom = None
pass
-print """
+print("""
===============================================================================
WARNING:
Usage of geompy.py is deprecated after SALOME V7.2!
It does not work in second, third, etc studies!
===============================================================================
-"""
+""")
if self.closed:
self.myCommand = self.myCommand + ":WF"
else:
- raise RuntimeError, "Sketcher2D.close() : can't build face on unclosed wire"
+ raise RuntimeError("Sketcher2D.close() : can't build face on unclosed wire")
from salome.geom.geomBuilder import ParseSketcherCommand, RaiseIfFailed
Command,Parameters = ParseSketcherCommand(self.myCommand)
OY = geompy.MakeVectorDXDYDZ(0, 1, 0)
OZ = geompy.MakeVectorDXDYDZ(0, 0, 1)
- v=range(8)
- l=range(8)
+ v=list(range(8))
+ l=list(range(8))
v0 = geompy.MakeVertex(0, 0, 0)
v[0] = geompy.MakeVertex(0, r1/2.0, 0)
v[1] = geompy.MakeVertex(0, r1, 0)
def pointsProjetes(study, vref, face):
#geompy = geomBuilder.New(study)
vface = geompy.ExtractShapes(face, geompy.ShapeType["VERTEX"], True)
- vord = range(len(vref))
+ vord = list(range(len(vref)))
plan = geompy.MakePlaneThreePnt(vref[0], vref[1], vref[-1], 10000)
vproj = [ geompy.MakeProjection(vert, plan) for vert in vface ]
for i,v in enumerate(vproj):
def arcsProjetes(study, vf, face):
#geompy = geomBuilder.New(study)
lface = geompy.ExtractShapes(face, geompy.ShapeType["EDGE"], True)
- lord = range(3)
+ lord = list(range(3))
ends = [vf[1], vf[6], vf[7], vf[3]]
for i in range(3):
for lf in lface:
if progressBar is not None:
time0 = time.time()
- print time.time() -time0
+ print(time.time() -time0)
if solid_thickness < 1e-7:
with_solid = False
h1, h2, a1)
if progressBar is not None:
progressBar.addSteps(2)
- print time.time() -time0
+ print(time.time() -time0)
if with_solid:
# The same code is executed again with different external radiuses in order
if progressBar is not None:
progressBar.addSteps(4)
- print time.time() -time0
+ print(time.time() -time0)
# --- extrusion droite des faces de jonction, pour reconstituer les demi cylindres
if with_solid:
if progressBar is not None:
progressBar.addSteps(1)
- print time.time() -time0
+ print(time.time() -time0)
extru1 = geompy.MakePrismVecH(sect45, OX, h1+10)
if progressBar is not None:
progressBar.addSteps(1)
- print time.time() -time0
+ print(time.time() -time0)
# --- partition et coupe
if progressBar is not None:
progressBar.addSteps(1)
- print time.time() -time0
+ print(time.time() -time0)
box = geompy.MakeBox(0, -2*(r1+h1), -2*(r1+h1), 2*(r1+h1), 2*(r1+h1), 2*(r1+h1))
rot = geompy.MakeRotation(box, OY, 45*math.pi/180.0)
if progressBar is not None:
progressBar.addSteps(9)
- print time.time() -time0
+ print(time.time() -time0)
faces_coupe = faci[:5]
if with_solid:
if progressBar is not None:
progressBar.addSteps(3)
- print time.time() -time0
+ print(time.time() -time0)
box = geompy.MakeBox(-1, -(r1+r2+2*solid_thickness), -1, h1, r1+r2+2*solid_thickness, h2)
if progressBar is not None:
progressBar.addSteps(5)
- print time.time() -time0
+ print(time.time() -time0)
# --- Partie inférieure
if progressBar is not None:
progressBar.addSteps(1)
- print time.time() -time0
+ print(time.time() -time0)
return final
for r1 in [1., 100.]:
for r2 in [0.9*r1, 0.5*r1, 0.1*r1, 0.05*r1]:
for thickness in [r1/100., r1/10., r1/2.]:
- print r1, r2, thickness
+ print(r1, r2, thickness)
h1 = r1 * 2.0
h2 = h1
try:
res = build_shape(theStudy, r1, r2, h1, h2, thickness)
geompy.addToStudy(res, "res_%f_%f_%f"%(r1,r2, thickness))
except:
- print "problem with res_%f_%f_%f"%(r1,r2, thickness)
+ print("problem with res_%f_%f_%f"%(r1,r2, thickness))
if __name__=="__main__":
"""For testing purpose"""