Merge Python 3 porting.

This commit is contained in:
rnv 2017-06-22 17:55:49 +03:00
commit 4b84d5ef39
52 changed files with 551 additions and 470 deletions

View File

@ -1,5 +1,4 @@
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
#! /usr/bin/env python3
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# This library is free software; you can redistribute it and/or
@ -58,7 +57,7 @@ def set_env( args ):
plugin_list.append("AdvancedGEOM")
# find additional plugins
for env_var in os.environ.keys():
for env_var in os.environ:
value = os.environ[env_var]
if env_var[-9:] == "_ROOT_DIR" and value:
plugin_root = value
@ -84,7 +83,7 @@ def set_env( args ):
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)

View File

@ -13,39 +13,39 @@ OXY = geompy.MakeVectorDXDYDZ(10,10,0)
# 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

View File

@ -10,15 +10,15 @@ import math
# 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.)

View File

@ -16,7 +16,7 @@ listChains = geompy.Propagate(check_box)
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

View File

@ -10,10 +10,10 @@ geompy = geomBuilder.New()
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)

View File

@ -11,13 +11,13 @@ import math
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)")

View File

@ -19,6 +19,6 @@ tolerance = 1e-5
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")

View File

@ -16,6 +16,6 @@ compound = geompy.MakeCompound([box, cylinder])
# 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")

View File

@ -16,6 +16,6 @@ compound = geompy.MakeCompound([box, cylinder])
# 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")

View File

@ -11,6 +11,6 @@ box = geompy.MakeBoxDXDYDZ(100,30,100)
(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")

View File

@ -13,10 +13,10 @@ cylinder = geompy.MakeCylinderRH(100, 300)
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)
@ -28,7 +28,7 @@ box2 = geompy.MakeBoxTwoPnt(Ver3, Ver4)
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)

View File

@ -19,17 +19,17 @@ for fi in range(len(faces)):
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

View File

@ -31,7 +31,7 @@ cut_without_f_2 = geompy.SuppressFaces(cut, [f_2])
# 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"])

View File

@ -9,9 +9,9 @@ geompy = geomBuilder.New()
# 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])

View File

@ -46,8 +46,8 @@ for i in range(nbSols):
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, ")")

View File

@ -14,8 +14,8 @@ faces = geompy.SubShapeAllSortedCentres(box, geompy.ShapeType["FACE"])
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")

View File

@ -18,8 +18,8 @@ tolerance = 1.e-07
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

View File

@ -18,12 +18,12 @@ face = geompy.MakeFace(wire, 1)
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"]
@ -32,13 +32,13 @@ Values = ["1e-7"]
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")

View File

@ -1,3 +1,4 @@
#!/usr/bin/env python3
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# This library is free software; you can redistribute it and/or
@ -17,7 +18,6 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
#!/usr/bin/env python
import unittest, sys, os

View File

@ -9,10 +9,10 @@ geompy = geomBuilder.New()
# 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])

View File

@ -9,5 +9,5 @@ geompy = geomBuilder.New()
# 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)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# This library is free software; you can redistribute it and/or
@ -49,106 +48,102 @@ import sys
import inspect
def generate(plugin_name, output):
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 )
functions = []
for attr in dir( mod ):
if attr.startswith( '_' ): continue # skip an internal methods
item = getattr( mod, attr )
if type( item ).__name__ == 'function':
if item not in functions:
functions.append( item )
pass
pass
pass
if functions:
for function in functions:
comments = inspect.getcomments(function)
if comments:
comments = comments.strip().split("\n")
comments = "\t" + "\n\t".join(comments)
output.append(comments)
pass
sources = inspect.getsource(function)
if sources is not None:
sources_list = sources.split("\n")
sources_new_list = []
found = False
for item in sources_list:
if '"""' in item:
if found == True:
found = False
continue
else:
found = True
continue
pass
pass
if found == False :
sources_new_list.append(item)
def get_functions(amodule):
for attr in dir(amodule):
if attr.startswith( '_' ): continue # skip an internal methods
item = getattr(amodule, attr)
if inspect.isfunction(item):
yield item
pass
pass
plugin_module_name = plugin_name + "Builder"
plugin_module = "salome.{}.{}".format(plugin_name, plugin_module_name)
import_str = "from salome.{} import {}".format(plugin_name, plugin_module_name)
execLine = "from salome.{} import {}\n" \
"import {}\n" \
"mod = {}".format(plugin_name, plugin_module_name, plugin_module, plugin_module)
print(execLine)
namespace = {}
exec(execLine , namespace)
for function in get_functions(namespace["mod"]):
comments = inspect.getcomments(function)
if comments:
comments = comments.strip().split("\n")
comments = "\t" + "\n\t".join(comments)
output.append(comments)
pass
sources = inspect.getsource(function)
if sources is not None:
sources_list = sources.split("\n")
sources_new_list = []
found = False
for item in sources_list:
if '"""' in item:
if found == True:
found = False
continue
else:
found = True
continue
pass
pass
if found == False:
sources_new_list.append(item)
pass
sources = "\n".join(sources_new_list)
sources = "\t" + sources.replace("\n", "\n\t")
output.append(sources)
pass
sources = "\n".join(sources_new_list)
sources = "\t" + sources.replace("\n", "\n\t")
output.append(sources)
pass
pass
pass
if __name__ == "__main__":
import optparse
parser = optparse.OptionParser(usage="%prog [options] plugin")
import argparse
parser = argparse.ArgumentParser()
h = "Output file (geomBuilder.py by default)"
parser.add_option("-o", "--output", dest="output",
action="store", default=None, metavar="file",
help=h)
parser.add_argument("-o", "--output", dest="output",
action="store", default='geomBuilder.py', metavar="file",
help=h)
h = "If this option is True, dummy help for geomBuiler class is added. "
h += "This option should be False (default) when building documentation for Geometry module "
h += "and True when building documentation for Geometry module plug-ins."
parser.add_option("-d", "--dummy-geom-help", dest="dummygeomhelp",
action="store_true", default=False,
help=h)
(options, args) = parser.parse_args()
if len( args ) < 1: sys.exit("Plugin name is not specified")
parser.add_argument("-d", "--dummy-geom-help", dest="dummygeomhelp",
action="store_true", default=False,
help=h)
parser.add_argument("plugin", nargs='+', help='Name of plugin')
args = parser.parse_args()
f = open(options.output, "w")
if len(args) > 1:
plugins_names = " ".join(args) + " plugins"
elif len(args) == 1:
plugins_names = args[0] + " plugin"
else:
plugins_names = ""
plugins_names = " ".join(args.plugin) + 'plugin'
if len(args.plugin) > 1:
plugins_names += 's'
output = []
if options.dummygeomhelp:
output.append( "## @package geomBuilder" )
output.append( "# Documentation of the methods dynamically added by the " + plugins_names + " to the @b %geomBuilder class." )
if args.dummygeomhelp:
output.append("## @package geomBuilder")
output.append("# Documentation of the methods dynamically added by the " + plugins_names + " to the @b %geomBuilder class.")
# Add dummy Geometry help
# This is supposed to be done when generating documentation for Geometry module plug-ins
output.append( "# @note The documentation below does not provide complete description of class @b %geomBuilder" )
output.append( "# from @b geomBuilder package. This documentation provides only information about" )
output.append( "# the methods dynamically added to the %geomBuilder class by the " + plugins_names + "." )
output.append( "# For more details on the %geomBuilder class, please refer to the SALOME %Geometry module" )
output.append( "# documentation." )
output.append("# @note The documentation below does not provide complete description of class @b %geomBuilder")
output.append("# from @b geomBuilder package. This documentation provides only information about")
output.append("# the methods dynamically added to the %geomBuilder class by the " + plugins_names + ".")
output.append("# For more details on the %geomBuilder class, please refer to the SALOME %Geometry module")
output.append("# documentation.")
pass
else:
# Extend documentation for geomBuilder class with information about dynamically added methods.
# This is supposed to be done only when building documentation for Geometry module
output.append( "## @package geomBuilder" )
output.append( "# @note Some methods are dynamically added to the @b %geomBuilder class in runtime by the" )
output.append( "# plug-in modules. If you fail to find help on some methods in the documentation of Geometry module, " )
output.append( "# try to look into the documentation for the Geometry module plug-ins." )
output.append("## @package geomBuilder")
output.append("# @note Some methods are dynamically added to the @b %geomBuilder class in runtime by the")
output.append("# plug-in modules. If you fail to find help on some methods in the documentation of Geometry module, ")
output.append("# try to look into the documentation for the Geometry module plug-ins.")
pass
output.append("class geomBuilder():")
for arg in args:
generate( arg, output )
pass
for plugin_name in args.plugin:
generate( plugin_name, output )
pass
for line in output: f.write( line + "\n" )
f.close()
with open(args.output, "w", encoding='utf8') as f:
f.write('\n'.join(output))

View File

@ -96,8 +96,7 @@ namespace
PyStdOut_write(PyStdOut* self, PyObject* args)
{
char *c;
int l;
if (!PyArg_ParseTuple(args, "t#:write", &c, &l))
if (!PyArg_ParseTuple(args, "s", &c))
return NULL;
*(self->out) = *(self->out) + c;
@ -121,8 +120,8 @@ namespace
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*/
@ -164,6 +163,14 @@ namespace
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
0, /*tp_version_tag*/
0, /*tp_finalize*/
};
PyObject* newPyStdOut( std::string& out )

View File

@ -66,6 +66,7 @@
#include <SALOMEDS_Tool.hxx>
#include <SALOMEDS_wrap.hxx>
#include <Basics_DirUtils.hxx>
#include <Basics_Utils.hxx>
#include <set>
#include <sstream>
@ -594,8 +595,8 @@ SALOMEDS::TMPFile* GEOM_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
// Prepare a file name to open
TCollection_AsciiString aNameWithExt("");
if (isMultiFile)
aNameWithExt = TCollection_AsciiString((char*)(SALOMEDS_Tool::GetNameFromPath
(getStudyServant()->URL())).c_str());
aNameWithExt = TCollection_AsciiString( (char*)(SALOMEDS_Tool::GetNameFromPath(
Kernel_Utils::encode(getStudyServant()->URL())).c_str()));
#if OCC_VERSION_MAJOR > 6
aNameWithExt += TCollection_AsciiString("_GEOM.cbf");
#else

View File

@ -329,7 +329,7 @@ def TEST_createBox():
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

View File

@ -137,11 +137,11 @@ def TEST_toString():
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()

View File

@ -247,7 +247,7 @@ class StructuralElementManager:
part = parts.__dict__[parttype](meshGroup,
groupGeomObj, newparams)
element.addPart(part)
except InvalidParameterError, e:
except InvalidParameterError as e:
logger.error("Invalid parameter error: %s" % e)
raise
except:
@ -295,7 +295,7 @@ class StructuralElementManager:
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
@ -370,13 +370,13 @@ class StructuralElement:
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]
@ -420,7 +420,7 @@ class StructuralElement:
: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, '
@ -434,8 +434,9 @@ class StructuralElement:
different parts of the structural element, and add them to the study.
"""
gg = salome.ImportComponentGUI("GEOM")
geompy = getGeompy()
for part in self._parts.itervalues():
for part in self._parts.values():
# Build the structural element part
logger.debug("Building %s" % part)
try:

View File

@ -82,13 +82,13 @@ class Orientation1D:
'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

View File

@ -45,7 +45,7 @@ from salome.kernel import termcolor
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"
@ -182,7 +182,7 @@ class StructuralElementPart:
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
@ -192,7 +192,7 @@ class StructuralElementPart:
"""
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
@ -453,7 +453,7 @@ class CircularBeam(Beam):
def __init__(self, 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
@ -565,7 +565,7 @@ class RectangularBeam(Beam):
def __init__(self, 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
@ -683,7 +683,7 @@ def getParameterInDict(nameList, parametersDict, default = None):
several different names.
"""
for name in nameList:
if parametersDict.has_key(name):
if name in parametersDict:
return parametersDict[name]
return default
@ -724,7 +724,7 @@ class GeneralBeam(RectangularBeam):
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

View File

@ -42,7 +42,7 @@ def ExportBREP(self, theObject, theFileName):
anOp = GetBREPPluginOperations(self)
anOp.ExportBREP(theObject, theFileName)
if anOp.IsDone() == 0:
raise RuntimeError, "Export : " + anOp.GetErrorCode()
raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass

View File

@ -47,12 +47,12 @@ obj5_entry = geompy.addToStudy(obj5, "Object5")
# 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(obj1_entry)
print "Information about second object: ", geompy.getObjectInfo(obj2_entry)
print "Information about third object: ", geompy.getObjectInfo(obj3_entry)
print "Information about fourth object: ", geompy.getObjectInfo(obj4_entry)
print "Information about fifth object: ", geompy.getObjectInfo(obj5_entry)
print("Information about first object: ", geompy.getObjectInfo(obj1_entry))
print("Information about second object: ", geompy.getObjectInfo(obj2_entry))
print("Information about third object: ", geompy.getObjectInfo(obj3_entry))
print("Information about fourth object: ", geompy.getObjectInfo(obj4_entry))
print("Information about fifth object: ", geompy.getObjectInfo(obj5_entry))
salome.sg.updateObjBrowser()

View File

@ -95,9 +95,9 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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
@ -287,7 +287,7 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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")
@ -301,18 +301,18 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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 ###
@ -345,7 +345,7 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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 ###
@ -358,7 +358,7 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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")
@ -370,7 +370,7 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
if isMeshTest == 1 and smesh is not None:
print "##################### Build Mesh #####################"
print("##################### Build Mesh #####################")
# ---- add a middle block of spanner handle in study
@ -392,76 +392,76 @@ def MakeSpanner (geompy, math, isBlocksTest = 0, isMeshTest = 0, smesh = None):
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

View File

@ -287,7 +287,7 @@ def TestAll (geompy, math):
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]))
@ -330,10 +330,10 @@ def TestAll (geompy, math):
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
@ -539,11 +539,11 @@ def TestAll (geompy, math):
# 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"])
@ -554,21 +554,21 @@ def TestAll (geompy, math):
# 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)
@ -596,4 +596,4 @@ def TestAll (geompy, math):
geompy.MakeExtraction(Box, [16], "Ext_no_vertex")
print "DONE"
print("DONE")

View File

@ -47,13 +47,13 @@ def CheckFieldCreation(shape, name, ftype, dimension, componentNames, nbFiOrMust
# 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
@ -70,13 +70,13 @@ def CheckFieldCreation(shape, name, ftype, dimension, componentNames, nbFiOrMust
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()
@ -138,12 +138,12 @@ def TestField (geomBuilder, math):
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
@ -159,7 +159,7 @@ def TestField (geomBuilder, math):
# 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")

View File

@ -51,12 +51,12 @@ def TestProcessShape (geompy):
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"]
@ -66,13 +66,13 @@ def TestProcessShape (geompy):
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")
@ -138,7 +138,7 @@ def TestSuppressInternalWires (geompy):
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, [])
@ -154,8 +154,8 @@ def TestSuppressInternalWires (geompy):
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")
@ -181,12 +181,12 @@ def TestCloseContour (geompy):
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
@ -202,13 +202,13 @@ def TestCloseContour (geompy):
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")
@ -243,7 +243,7 @@ def TestSuppressHoles (geompy):
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])
@ -258,7 +258,7 @@ def TestSuppressHoles (geompy):
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])
@ -274,7 +274,7 @@ def TestSuppressHoles (geompy):
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])

View File

@ -43,58 +43,58 @@ def TestMeasureOperations (geompy, math):
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))
@ -102,53 +102,53 @@ def TestMeasureOperations (geompy, math):
#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 #######
@ -156,11 +156,11 @@ def TestMeasureOperations (geompy, math):
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:
@ -175,11 +175,11 @@ def TestMeasureOperations (geompy, math):
#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)
@ -199,49 +199,49 @@ def TestMeasureOperations (geompy, math):
# 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

View File

@ -34,7 +34,7 @@ import GEOM
def TestExportImport (geompy, shape):
print "Test Export/Import ...",
print("Test Export/Import ...", end=' ')
tmpDir = os.getenv("TEMP")
if tmpDir == None:
@ -109,7 +109,7 @@ def TestExportImport (geompy, shape):
aNewShape = geompy.RestoreShape(aStream)
geompy.addToStudy(aNewShape, "aNewShape")
print "OK"
print("OK")
def TestOtherOperations (geompy, math):
@ -239,19 +239,19 @@ 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])
@ -274,20 +274,20 @@ def TestOtherOperations (geompy, math):
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)
@ -325,10 +325,10 @@ def TestOtherOperations (geompy, math):
# 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)
@ -343,10 +343,10 @@ def TestOtherOperations (geompy, math):
# 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"])
@ -391,7 +391,7 @@ def TestOtherOperations (geompy, math):
'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)
@ -550,7 +550,7 @@ def TestOtherOperations (geompy, math):
geompy.ShapeType["FACE"])
ind = 1
for shFace in sharedFaces:
geompy.addToStudy(shFace, "sharedFace_" + `ind`)
geompy.addToStudy(shFace, "sharedFace_" + repr(ind))
ind = ind + 1
pass
@ -558,7 +558,7 @@ def TestOtherOperations (geompy, math):
geompy.ShapeType["EDGE"])
ind = 1
for shEdge in sharedEdges:
geompy.addToStudy(shEdge, "sharedEdge_" + `ind`)
geompy.addToStudy(shEdge, "sharedEdge_" + repr(ind))
ind = ind + 1
pass
@ -713,7 +713,7 @@ def TestOtherOperations (geompy, math):
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"],
@ -728,7 +728,7 @@ def TestOtherOperations (geompy, math):
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"],
@ -754,7 +754,7 @@ def TestOtherOperations (geompy, math):
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"],
@ -768,7 +768,7 @@ def TestOtherOperations (geompy, math):
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)
@ -784,8 +784,8 @@ def TestOtherOperations (geompy, math):
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
@ -799,10 +799,10 @@ def TestOtherOperations (geompy, math):
# 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
@ -816,15 +816,15 @@ def TestOtherOperations (geompy, math):
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)

View File

@ -41,7 +41,7 @@ while ind < 5:
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)

View File

@ -42,7 +42,7 @@ while ind < 6:
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)

View File

@ -31,7 +31,7 @@
from launchConfigureParser import verbose
if verbose(): print "============== import GEOM ======================="
if verbose(): print("============== import GEOM =======================")
import GEOM

View File

@ -46,7 +46,7 @@ def ExportIGES(self, theObject, theFileName, theVersion="5.1"):
anOp = GetIGESPluginOperations(self)
anOp.ExportIGES(theObject, theFileName, theVersion)
if anOp.IsDone() == 0:
raise RuntimeError, "Export : " + anOp.GetErrorCode()
raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
@ -96,7 +96,7 @@ def ImportIGES(self, theFileName, theIsIgnoreUnits = False, theName=None):
anIsIgnoreUnits = theIsIgnoreUnits
aName = theName
if isinstance( theIsIgnoreUnits, basestring ):
if isinstance( theIsIgnoreUnits, str ):
anIsIgnoreUnits = False
aName = theIsIgnoreUnits
pass

View File

@ -82,7 +82,7 @@ if os.access(theFilenameToSave, os.F_OK):
os.remove(theFilenameToSave)
salome.myStudy.SaveAs(theFilenameToSave, 0, 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.myStudy.SaveAs(theFilenameToSave, 0, 0)

View File

@ -45,7 +45,7 @@ def ExportSTEP(self, theObject, theFileName, theUnit=GEOM.LU_METER):
anOp = GetSTEPPluginOperations(self)
anOp.ExportSTEP(theObject, theFileName, theUnit)
if anOp.IsDone() == 0:
raise RuntimeError, "Export : " + anOp.GetErrorCode()
raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass
@ -103,11 +103,11 @@ def ImportSTEP(self, theFileName, theIsIgnoreUnits = False,
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

View File

@ -52,7 +52,7 @@ def ExportSTL(self, theObject, theFileName, theIsASCII = True, theDeflection = 0
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

View File

@ -45,6 +45,6 @@ def ExportVTK(self, theObject, theFileName, theDeflection=0.001):
anOp = GetVTKPluginOperations(self)
anOp.ExportVTK(theObject, theFileName, theDeflection)
if anOp.IsDone() == 0:
raise RuntimeError, "Export : " + anOp.GetErrorCode()
raise RuntimeError("Export : " + anOp.GetErrorCode())
pass
pass

View File

@ -240,6 +240,8 @@
## @}
import omniORB
# initialize SALOME session in try/except block
# to avoid problems in some cases, e.g. when generating documentation
try:
@ -258,11 +260,89 @@ import functools
from salome.geom.gsketcher import Sketcher3D, Sketcher2D, Polyline2D
# In case the omniORBpy EnumItem class does not fully support Python 3
# (for instance in version 4.2.1-2), the comparison ordering methods must be
# defined
#
try:
GEOM.COMPOUND < GEOM.SOLID
except TypeError:
def enumitem_eq(self, other):
try:
if isinstance(other, omniORB.EnumItem):
if other._parent_id == self._parent_id:
return self._v == other._v
else:
return self._parent_id == other._parent_id
else:
return id(self) == id(other)
except:
return id(self) == id(other)
def enumitem_lt(self, other):
try:
if isinstance(other, omniORB.EnumItem):
if other._parent_id == self._parent_id:
return self._v < other._v
else:
return self._parent_id < other._parent_id
else:
return id(self) < id(other)
except:
return id(self) < id(other)
def enumitem_le(self, other):
try:
if isinstance(other, omniORB.EnumItem):
if other._parent_id == self._parent_id:
return self._v <= other._v
else:
return self._parent_id <= other._parent_id
else:
return id(self) <= id(other)
except:
return id(self) <= id(other)
def enumitem_gt(self, other):
try:
if isinstance(other, omniORB.EnumItem):
if other._parent_id == self._parent_id:
return self._v > other._v
else:
return self._parent_id > other._parent_id
else:
return id(self) > id(other)
except:
return id(self) > id(other)
def enumitem_ge(self, other):
try:
if isinstance(other, omniORB.EnumItem):
if other._parent_id == self._parent_id:
return self._v >= other._v
else:
return self._parent_id >= other._parent_id
else:
return id(self) >= id(other)
except:
return id(self) >= id(other)
GEOM.omniORB.EnumItem.__eq__ = enumitem_eq
GEOM.omniORB.EnumItem.__lt__ = enumitem_lt
GEOM.omniORB.EnumItem.__le__ = enumitem_le
GEOM.omniORB.EnumItem.__gt__ = enumitem_gt
GEOM.omniORB.EnumItem.__ge__ = enumitem_ge
omniORB.EnumItem.__eq__ = enumitem_eq
omniORB.EnumItem.__lt__ = enumitem_lt
omniORB.EnumItem.__le__ = enumitem_le
omniORB.EnumItem.__gt__ = enumitem_gt
omniORB.EnumItem.__ge__ = enumitem_ge
# service function
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)
@ -296,7 +376,7 @@ def ManageTransactions(theOpeName):
## @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
@ -316,7 +396,7 @@ def ParseParameters(*parameters):
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)
@ -365,7 +445,7 @@ def ParseSketcherCommand(command):
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:
@ -554,7 +634,7 @@ engine = None
doLcc = False
created = False
class geomBuilder(object, GEOM._objref_GEOM_Gen):
class geomBuilder(GEOM._objref_GEOM_Gen):
## Enumeration ShapeType as a dictionary. \n
## Topological types of shapes (like Open Cascade types). See GEOM::shape_type for details.
@ -605,7 +685,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
# @ingroup l1_geomBuilder_auxiliary
kind = GEOM.GEOM_IKindOfShape
def __new__(cls):
def __new__(cls, *args):
global engine
global geom
global doLcc
@ -644,12 +724,12 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
#print "return geom 2 ", geom
return geom
def __init__(self):
def __init__(self, *args):
global created
#print "-------- geomBuilder __init__ --- ", created, self
if not created:
created = True
GEOM._objref_GEOM_Gen.__init__(self)
GEOM._objref_GEOM_Gen.__init__(self, *args)
self.myMaxNbSubShapesAllowed = 0 # auto-publishing is disabled by default
self.myBuilder = None
self.father = None
@ -685,10 +765,10 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
# ---
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]
@ -733,7 +813,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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:
@ -897,7 +977,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
self.RestoreSubShapesSO(aSObject, theArgs,
theFindMethod, theInheritFirstArg, True )
except:
print "addToStudy() failed"
print("addToStudy() failed")
return ""
return aShape.GetStudyEntry()
@ -927,7 +1007,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
aSObject = self.AddInStudy(aShape, aName, aFather)
if aSObject and aName: aSObject.SetAttrString("AttributeName", aName)
except:
print "addToStudyInFather() failed"
print("addToStudyInFather() failed")
return ""
return aShape.GetStudyEntry()
@ -3067,14 +3147,14 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -3153,7 +3233,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -4210,11 +4290,11 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -4702,7 +4782,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
# 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")
@ -4744,7 +4824,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
# 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")
@ -4891,7 +4971,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
#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")
@ -7439,7 +7519,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -7521,7 +7601,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -7553,7 +7633,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -7623,7 +7703,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
"""
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
@ -8143,7 +8223,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
if Limit == self.ShapeType["AUTO"]:
# automatic detection of the most appropriate shape limit type
lim = GEOM.SHAPE
for s in ListShapes: lim = min( lim, s.GetMaxShapeType() )
for s in ListShapes: lim = min(lim, s.GetMaxShapeType())
Limit = EnumToLong(lim)
pass
anObj = self.BoolOp.MakePartition(ListShapes, ListTools,
@ -8216,7 +8296,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
if Limit == self.ShapeType["AUTO"]:
# automatic detection of the most appropriate shape limit type
lim = GEOM.SHAPE
for s in ListShapes: lim = min( lim, s.GetMaxShapeType() )
for s in ListShapes: lim = min(lim, s.GetMaxShapeType())
Limit = EnumToLong(lim)
pass
anObj = self.BoolOp.MakePartitionNonSelfIntersectedShape(ListShapes, ListTools,
@ -9801,7 +9881,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
"""
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.
@ -9815,7 +9895,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -9835,7 +9915,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -9853,7 +9933,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -11314,7 +11394,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
Descr = self.MeasuOp.PrintShapeErrors(theShape, theShapeErrors)
if theReturnStatus == 1:
return Descr
print Descr
print(Descr)
pass
## Check a topology of the given shape.
@ -11369,7 +11449,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -11660,10 +11740,10 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -11719,7 +11799,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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)
@ -11754,13 +11834,13 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -12363,7 +12443,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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.
@ -13387,7 +13467,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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()
@ -13420,10 +13500,10 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
"""
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)
@ -13436,8 +13516,8 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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()
@ -13704,7 +13784,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
"""
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)
@ -13723,7 +13803,7 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
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
@ -13754,7 +13834,6 @@ class geomBuilder(object, GEOM._objref_GEOM_Gen):
## @}
import omniORB
# Register the new proxy for GEOM_Gen
omniORB.registerObjref(GEOM._objref_GEOM_Gen._NP_RepositoryId, geomBuilder)
@ -13763,8 +13842,8 @@ omniORB.registerObjref(GEOM._objref_GEOM_Gen._NP_RepositoryId, geomBuilder)
# @ingroup l2_field
class geomField( GEOM._objref_GEOM_Field ):
def __init__(self):
GEOM._objref_GEOM_Field.__init__(self)
def __init__(self, *args):
GEOM._objref_GEOM_Field.__init__(self, *args)
self.field = GEOM._objref_GEOM_Field
return
@ -13781,7 +13860,7 @@ class geomField( GEOM._objref_GEOM_Field ):
## Returns type of field data as integer [0-3]
def getType(self):
"Returns type of field data"
return self.field.GetDataType(self)._v
return EnumToLong(self.field.GetDataType(self))
## Returns type of field data:
# one of GEOM.FDT_Bool, GEOM.FDT_Int, GEOM.FDT_Double, GEOM.FDT_String
@ -13809,8 +13888,7 @@ class geomField( GEOM._objref_GEOM_Field ):
"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 )
@ -13848,7 +13926,7 @@ class geomField( GEOM._objref_GEOM_Field ):
"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
@ -13873,19 +13951,19 @@ class geomField( GEOM._objref_GEOM_Field ):
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
@ -13941,15 +14019,15 @@ plugins_var = os.environ.get( "GEOM_PluginsList" )
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 )

View File

@ -41,19 +41,19 @@ try:
# 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!
@ -80,4 +80,4 @@ The geompy.py module works correctly only in first created study.
It does not work in second, third, etc studies!
===============================================================================
"""
""")

View File

@ -1207,7 +1207,7 @@ class Sketcher2D:
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)

View File

@ -42,7 +42,7 @@ INCLUDE_DIRECTORIES(
# swig flags
SET_SOURCE_FILES_PROPERTIES(libGEOM_Swig.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(libGEOM_Swig.i PROPERTIES SWIG_DEFINITIONS "-shadow")
SET_SOURCE_FILES_PROPERTIES(libGEOM_Swig.i PROPERTIES SWIG_FLAGS "-py3")
SET_SOURCE_FILES_PROPERTIES(libGEOM_SwigPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "-DHAVE_CONFIG_H")
# additional preprocessor / compiler flags

View File

@ -40,8 +40,8 @@ def demidisk(r1, a1, roty=0, solid_thickness=0):
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)
@ -101,7 +101,7 @@ def demidisk(r1, a1, roty=0, solid_thickness=0):
def pointsProjetes(vref, face):
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):
@ -113,7 +113,7 @@ def pointsProjetes(vref, face):
def arcsProjetes(vf, face):
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:
@ -131,7 +131,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
time0 = time.time()
print time.time() -time0
print(time.time() -time0)
if solid_thickness < 1e-7:
with_solid = False
@ -157,7 +157,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
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
@ -175,7 +175,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
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:
@ -184,7 +184,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
progressBar.addSteps(1)
print time.time() -time0
print(time.time() -time0)
extru1 = geompy.MakePrismVecH(sect45, OX, h1+10)
@ -196,7 +196,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
progressBar.addSteps(1)
print time.time() -time0
print(time.time() -time0)
# --- partition et coupe
@ -208,7 +208,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
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)
@ -218,7 +218,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
progressBar.addSteps(9)
print time.time() -time0
print(time.time() -time0)
faces_coupe = faci[:5]
if with_solid:
@ -229,7 +229,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
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)
@ -238,7 +238,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
progressBar.addSteps(5)
print time.time() -time0
print(time.time() -time0)
# --- Partie inférieure
@ -255,7 +255,7 @@ def build_shape(r1, r2, h1, h2, solid_thickness=0, progressBar=None ):
if progressBar is not None:
progressBar.addSteps(1)
print time.time() -time0
print(time.time() -time0)
return final
@ -389,14 +389,14 @@ def test_t_shape_builder():
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(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"""

View File

@ -22,7 +22,7 @@
import sys
from qtsalome import *
from t_shape_dialog_ui import Ui_Dialog
from salome.geom.t_shape.t_shape_dialog_ui import Ui_Dialog
class TShapeDialog(Ui_Dialog,QWidget):

View File

@ -52,7 +52,7 @@ SET(_swig_SCRIPTS
# swig flags
SET_SOURCE_FILES_PROPERTIES(xao.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(xao.i PROPERTIES SWIG_DEFINITIONS "-shadow")
SET_SOURCE_FILES_PROPERTIES(xao.i PROPERTIES SWIG_FLAGS "-py3")
#SET_SOURCE_FILES_PROPERTIES(xao_wrap.cxx PROPERTIES COMPILE_FLAGS "-DHAVE_CONFIG_H")
# --- rules ---