ids2D=numberOf3DVolSharing.findIdsEqual(1)
skin_V650=m2D[ids2D]
# We can check if the two skins are identical
-print "Are two meshes equal between V660 and V650 ?",skin.isEqual(skin_V650,1e-12)
+print("Are two meshes equal between V660 and V650 ?",skin.isEqual(skin_V650,1e-12))
# The argument can be a scalar or a list, we have to check
# that first.
if isIterable(x):
- y = map(self,x)
+ y = list(map(self,x))
else:
y = self.function(x, **self.kwargs)
return y
try:
len(x)
return True
- except TypeError, e:
+ except TypeError as e:
return False
#
y=1
return y
-import lagrange
+from . import lagrange
class FuncLagrange(Function):
def __init__(self,points):
"""
x=2
y_ref = 3.*x+7.
y_res = f(x)
- print y_ref
- print y_res
+ print(y_ref)
+ print(y_res)
if y_ref != y_res:
- print "ERR"
+ print("ERR")
else:
- print "OK"
+ print("OK")
def TEST_Function_withIterable():
f=MyFunction(a=3.,b=1.)
arrY = f(arrX)
arrY_ref = [1., 4., 7., 10.]
- print "arrY res =%s"%arrY
- print "arrY ref =%s"%arrY_ref
+ print("arrY res =%s"%arrY)
+ print("arrY ref =%s"%arrY_ref)
def TEST_FuncConique():
f=FuncConique(xlimit=0.3)
- from plotter import plot
+ from .plotter import plot
plot(f)
def TEST_FuncChapeau():
f=FuncChapeau(xlimit=0.3)
- from plotter import plot
+ from .plotter import plot
plot(f)
def TEST_FuncStiffExp():
f=FuncStiffExp(xlimit=0.3,stiffness=20.)
- from plotter import plot
+ from .plotter import plot
plot(f)
def TEST_FuncCosinus():
f=FuncCosinus(nbPeriods=20)
- from plotter import plot
+ from .plotter import plot
plot(f, step=0.001)
def TEST_FuncStiffPulse():
f=FuncStiffPulse(xlimit=0.3,stiffness=50,nbPeriods=15)
- from plotter import plot
+ from .plotter import plot
plot(f, step=0.001)
def TEST_FuncHeaviside():
f=FuncHeaviside(xlimit=0.3)
- from plotter import plot
+ from .plotter import plot
plot(f)
def TEST_FuncPorte():
f=FuncPorte(xinf=0.3,xsup=0.4)
- from plotter import plot
+ from .plotter import plot
plot(f)
def TEST_customize_01():
y=5*f(x)+2
return y
- from plotter import plot
+ from .plotter import plot
plot(myfunc, step=0.001)
def TEST_customize_02():
y=1-f(x)
return y
- from plotter import plot
+ from .plotter import plot
plot(myfunc)
def TEST_FuncLagrange():
points = {0.:5, 0.2:10, 0.9:10, 0.6:21, 1:8}
f=FuncLagrange(points)
- from plotter import plot
+ from .plotter import plot
plot(f)
if __name__ == "__main__":
tmp = scipy.poly1d([0])
result=scipy.poly1d([0])
- for i in points.keys():
+ for i in points:
numerator=scipy.poly1d([1])
denom = 1.0
- for j in points.keys():
+ for j in points:
if (i != j):
tmp = scipy.poly1d([1,-j])
numerator = numerator * tmp
def sortdict(points):
# Sort this dictionary by keys and returns 2 lists, the list of X
# and the list of Y, the whole ordered by X
- keys = points.keys()
- keys.sort()
+ keys = sorted(list(points.keys()))
return keys, [points[key] for key in keys]
import pylab
"""
arrX=numpy.arange(start, stop, step, dtype='float64')
# function is a callable
- arrY=map(function,arrX)
+ arrY=list(map(function,arrX))
pylab.plot(arrX, arrY)
pylab.show()
def TEST_lagrange_01():
input = {0.:5, 0.2:10, 0.9:10, 0.6:21, 1:8}
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
def TEST_lagrange_02():
input = {0.:0., 0.5:1., 1.:0.}
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
# ---
arrY = [5, 10, 10, 21, 8]
input = points_usingarray(arrX,arrY)
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
# Another example using numpy
arrY[3]=2
input = points_usingarray(arrX,arrY)
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
# ---
arrY=numpy.cos(10*arrX)
input = points_usingarray(arrX,arrY)
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
# General method
arrX=numpy.arange(start=0., stop=1., step=0.1, dtype='float64')
input = points_usingfunction(arrX,chapeau)
polynom = lagrange(input)
- print polynom
+ print(polynom)
plot(function=polynom, start=0., stop=1., step=0.001)
"""
arrX=numpy.arange(start, stop, step, dtype='float64')
# function is a callable
- arrY=map(function,arrX)
+ arrY=list(map(function,arrX))
pylab.plot(arrX, arrY)
pylab.show()
targetMesh.setName("MyMesh3D");
targetMesh.setDescription("build3DMesh");
targetMesh.allocateCells(12);
- for i in xrange(8):
+ for i in range(8):
targetMesh.insertNextCell(NORM_HEXA8,8,targetConn[8*i:8*(i+1)]);
pass
targetMesh.finishInsertingCells();
field=MEDCouplingFieldDouble.New(ON_NODES,ONE_TIME)
field.setMesh(m)
da=DataArrayDouble.New()
- da.setValues([float(3*i) for i in xrange(27)],27,1)
+ da.setValues([float(3*i) for i in range(27)],27,1)
field.setArray(da)
field.setName("vitooNode")
field.setTime(4.7,9,14)
m=createALocalMesh()
nbOfFields=100
fs=nbOfFields*[None]
- for i in xrange(nbOfFields):
+ for i in range(nbOfFields):
fs[i]=MEDCouplingFieldDouble.New(ON_CELLS,ONE_TIME)
fs[i].setMesh(m)
da=DataArrayDouble.New()
field.setMesh(m)
da=DataArrayDouble.New()
field.setTime(14.5,0,0)
- da.setValues([float(7*i) for i in xrange(24)],24,1)
+ da.setValues([float(7*i) for i in range(24)],24,1)
field.setName("MeshOnCMesh");
field.setArray(da)
return field;
meshCorba=MEDCouplingUMeshServant._this(createALocalMesh())
ior=orb.object_to_string(meshCorba)
-print "mesh : ",ior
+print("mesh : ",ior)
f1=MEDCouplingFieldDoubleServant._this(createALocalField1())
ior2=orb.object_to_string(f1)
-print "Field on cell ",ior2
+print("Field on cell ",ior2)
f2=MEDCouplingFieldDoubleServant._this(createALocalField2())
ior3=orb.object_to_string(f2)
-print "Field on node ",ior3
+print("Field on node ",ior3)
fs3=MEDCouplingFieldOverTimeServant._this(createALocalMultiField3())
fs3.Register()
ior4=orb.object_to_string(fs3)
-print "Fields over time ",ior4
+print("Fields over time ",ior4)
m2=MEDCouplingCMeshServant._this(createALocalCMesh4())
ior5=orb.object_to_string(m2)
-print "CMesh 2 : ",ior5
+print("CMesh 2 : ",ior5)
f5=MEDCouplingFieldDoubleServant._this(createALocalField5())
ior6=orb.object_to_string(f5)
-print "Field on cell CMesh ",ior6
+print("Field on cell CMesh ",ior6)
script="""
src1 = ParaMEDCorbaPluginSource()
cartesian mesh as a grid with nbCellsX segments in the X direction
and nbCellsY in the Y direction (nb. cells = nbCellsX * nbCellsY)
"""
- print "Creating grid mesh of size %sx%s"%(nbCellsX, nbCellsY)
+ print("Creating grid mesh of size %sx%s"%(nbCellsX, nbCellsY))
cmesh=MC.MEDCouplingCMesh.New();
# Create X coordinates
Convert the cartesian mesh in unstructured mesh for the need of
write function of MEDLoader
"""
- print "Creating unstructured mesh from %s"%(cartesianMesh.getName())
+ print("Creating unstructured mesh from %s"%(cartesianMesh.getName()))
umesh=cartesianMesh.buildUnstructured();
umesh.setName(cartesianMesh.getName())
return umesh
nodes. In any case, it must be consistent with the dimensions of
the numpy 2D array.
"""
- print "Creating field %s with iteration=%s"%(fieldName,iteration)
+ print("Creating field %s with iteration=%s"%(fieldName,iteration))
# The sizes are deduced from the numpy array. Note that if
# typeOfField is ON_CELLS, then the size should correspond to the
# A function can be a simple python function ...
def f1(x,y):
z = 10*x
- print "x=%s\ny=%s\nz=%s"%(x,y,z)
+ print("x=%s\ny=%s\nz=%s"%(x,y,z))
return z
# ... but also a more sophisticated callable object, for example to
def function(self, x,y):
z = self.param*x
- print "x=%s\ny=%s\nz=%s"%(x,y,z)
+ print("x=%s\ny=%s\nz=%s"%(x,y,z))
return z
def __call__(self, x,y):
#im=Image.open("images/lena.png")
#image=pilutil.fromimage(im,True)
#image=numpy.asarray(im)
-#print image
+# print(image)
dim = len(image.shape)
-print "Image space dimension = %d"%dim
+print("Image space dimension = %d"%dim)
sizeX = image.shape[1]
sizeY = image.shape[0]
# double as required by the MEDCoupling field specification.
import numpy
imageDataNArray = image.reshape(1,sizeX*sizeY)[0]
-print imageDataNArray
+print(imageDataNArray)
imageDataNArrayDouble = numpy.array(imageDataNArray, dtype='float64')
imageDataArrayDouble = list(imageDataNArrayDouble)
coordsY.setValues(arrY,nbNodesY,1)
cmesh.setCoords(coordsX,coordsY)
-print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension()
+print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension())
# WARN: In the current state of development of MEDLoader, only
# unstructured meshes are supported for writting function in med
nbNodesX = sizeX+1
stepX = 0.1
arrX = [float(i * stepX) for i in range(nbNodesX)]
-print "Size of arrX = %d"%len(arrX)
+print("Size of arrX = %d"%len(arrX))
coordsX=MC.DataArrayDouble.New()
coordsX.setValues(arrX,nbNodesX,1)
coordsY.setValues(arrY,sizeY,1)
cmesh.setCoords(coordsX,coordsY)
-print cmesh.getSpaceDimension()
-#print cmesh
+print(cmesh.getSpaceDimension())
+# print(cmesh)
# WARN: In the current state of development of MEDLoader, only
# unstructured meshes are supported for writting function in med
# Get the data
imgdata=imgbw.getdata()
width,height=imgbw.size
- print list(imgdata)
- print width,height
+ print(list(imgdata))
+ print(width,height)
# Convert the data in a matrix using numpy
tab=numpy.array(imgdata,dtype='float64')
- print list(tab)
- print tab
+ print(list(tab))
+ print(tab)
nbRows=height
nbCols=width
matrix=numpy.reshape(tab,(nbRows,nbCols))
# Note that in the reshape function, the height (sizeY) of the image
# is specified first, because it corresponds to the number of rows.
- print matrix
- print list(matrix)
+ print(matrix)
+ print(list(matrix))
import MEDCoupling as MC
import MEDLoader as ML
coordsY.setValues(arrY,nbNodesY,1)
cmesh.setCoords(coordsX,coordsY)
- print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension()
+ print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension())
# WARN: In the current state of development of MEDLoader, only
# unstructured meshes are supported for writting function in med
# Load as an unstructured mesh
meshDimRelToMax = 0 # 0 = no restriction
umesh = MEDLoader.ReadUMeshFromFile(filepath,meshName,meshDimRelToMax)
-print "umesh is structured: %s"%umesh.isStructured()
+print("umesh is structured: %s"%umesh.isStructured())
# Load as a structured mesh explicitly
# _T2A
cmesh = medfile.getMesh()
# Note that the getMesh method is a short way to the method:
#cmesh = medfile.getGenMeshAtLevel(0,False)
-print "cmesh is structured: %s"%cmesh.isStructured()
+print("cmesh is structured: %s"%cmesh.isStructured())
# _T2B
# Load and let MEDLoader decide what is nature of the mesh
# _T1A
from MEDLoader import MEDFileMesh
medfile = MEDFileMesh.New(filepath,meshName)
-print medfile.advancedRepr()
+print(medfile.advancedRepr())
meshDimRelToMax = 0 # 0 = no restriction
mesh = medfile.getGenMeshAtLevel(meshDimRelToMax)
-print "mesh is structured: %s"%mesh.isStructured()
+print("mesh is structured: %s"%mesh.isStructured())
# _T1B
# test to reload the mesh
medfile = MEDFileCMesh.New(outputfilepath,meshName)
cmesh = medfile.getMesh()
-print "cmesh is structured: %s"%cmesh.isStructured()
+print("cmesh is structured: %s"%cmesh.isStructured())
# Q: Is it possible to know if a mesh is structured or unstructured
# without loading the mesh.
for meshName in meshNames:
- print "%s"%meshName
+ print("%s"%meshName)
# At this step, one can load the mesh of name meshName (but it is
# not an obligation to continue to explore the metadata)
for fieldName in fieldNames:
- print " %s"%fieldName
+ print(" %s"%fieldName)
# A field name could identify several MEDCoupling fields, that
# differ by their spatial discretization on the mesh (values on
listOfTypes = MEDLoader.GetTypesOfField(filepath,meshName,fieldName)
for typeOfDiscretization in listOfTypes:
- print " %s"%typeOfDiscretization
+ print(" %s"%typeOfDiscretization)
# Then, we can get the iterations associated to this field on
# this type of spatial discretization:
for fieldIteration in fieldIterations:
itNumber = fieldIteration[0]
itOrder = fieldIteration[1]
- print " (%s,%s)"%(itNumber,itOrder)
+ print(" (%s,%s)"%(itNumber,itOrder))
if READ_PHYSICAL_DATA:
medCouplingField = MEDLoader.ReadField(typeOfDiscretization,
fieldName,
itNumber,
itOrder)
- print medCouplingField
+ print(medCouplingField)
# request all the fields for a given iteration step, then we should
# use the iteration step as a first classifaction switch of the tree
-print fieldTree.keys()
+print(list(fieldTree.keys()))
# _T3A
-for meshName in fieldTree.keys():
- print "%s"%meshName
- for fieldName in fieldTree[meshName].keys():
- print " %s"%fieldName
- for fieldType in fieldTree[meshName][fieldName].keys():
- print " %s"%fieldType
- for itNumber in fieldTree[meshName][fieldName][fieldType].keys():
- for itOrder in fieldTree[meshName][fieldName][fieldType][itNumber].keys():
- print " (%s,%s)"%(itNumber,itOrder)
- print fieldTree[meshName][fieldName][fieldType][itNumber][itOrder]
+for meshName in list(fieldTree.keys()):
+ print("%s"%meshName)
+ for fieldName in list(fieldTree[meshName].keys()):
+ print(" %s"%fieldName)
+ for fieldType in list(fieldTree[meshName][fieldName].keys()):
+ print(" %s"%fieldType)
+ for itNumber in list(fieldTree[meshName][fieldName][fieldType].keys()):
+ for itOrder in list(fieldTree[meshName][fieldName][fieldType][itNumber].keys()):
+ print(" (%s,%s)"%(itNumber,itOrder))
+ print(fieldTree[meshName][fieldName][fieldType][itNumber][itOrder])
# _T3B
x=0.5
y=0.5
fieldValue = fieldOnNodes.getValueOn([x,y])
-print fieldValue
+print(fieldValue)
#include <sstream>
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
+{
+ return _Py_wchar2char(text, error_pos);
+}
+#endif
+
const std::string MEDPresentation::PROP_NAME = "name";
const std::string MEDPresentation::PROP_NB_COMPONENTS = "nbComponents";
const std::string MEDPresentation::PROP_SELECTED_COMPONENT = "selectedComponent";
execPyLine(oss.str());
PyObject* p_obj = getPythonObjectFromMain("__nbCompo");
long nbCompo;
- if (p_obj && PyInt_Check(p_obj))
- nbCompo = PyInt_AS_LONG(p_obj);
+ if (p_obj && PyLong_Check(p_obj))
+ nbCompo = PyLong_AS_LONG(p_obj);
else
{
STDLOG("Unexpected Python error");
execPyLine(oss2.str());
PyObject* p_obj = getPythonObjectFromMain("__compo");
std::string compo;
- if (p_obj && PyString_Check(p_obj))
- compo = std::string(PyString_AsString(p_obj)); // pointing to internal Python memory, so make a copy!!
+ if (p_obj && PyUnicode_Check(p_obj))
+ compo = std::string(Py_EncodeLocale(PyUnicode_AS_UNICODE(p_obj), NULL)); // pointing to internal Python memory, so make a copy!!
else
{
STDLOG("Unexpected Python error");
try:
MED_ROOT_DIR=os.environ["MED_ROOT_DIR"]
-except KeyError, e:
+except KeyError as e:
raise RuntimeError("MED_ROOT_DIR should be defined to load the test data")
RESDIR=os.path.join(MED_ROOT_DIR,"share","salome","resources","med","medcalc_testfiles")
dataManager = factory.getDataManager()
datasource = dataManager.loadDatasource(testFilePath)
if datasource.name != testFileName:
- print "ERR: datasource.name=%s (should be %s)"%(datasource.name,testFilePath)
+ print("ERR: datasource.name=%s (should be %s)"%(datasource.name,testFilePath))
return False
# We try to load the file twice. It should not load twice and
sourceid_ref = datasource.id
datasource = dataManager.loadDatasource(testFilePath)
if datasource.id != sourceid_ref:
- print "ERR: datasource.id=%s (should be %s)"%(datasource.id,sourceid_ref)
+ print("ERR: datasource.id=%s (should be %s)"%(datasource.id,sourceid_ref))
return False
return True
fieldHandlerList = dataManager.getFieldHandlerList()
fieldHandler0 = fieldHandlerList[0]
- print dataManager.getFieldRepresentation(fieldHandler0.id)
+ print(dataManager.getFieldRepresentation(fieldHandler0.id))
return True
def TEST_updateFieldMetadata():
fieldHandler0.source)
fieldHandlerModified = dataManager.getFieldHandler(fieldid)
- print fieldHandlerModified
+ print(fieldHandlerModified)
if fieldHandlerModified.fieldname != newname:
- print "ERR: the name is %s (should be %s)"%(fieldHandlerModified.fieldname,newname)
+ print("ERR: the name is %s (should be %s)"%(fieldHandlerModified.fieldname,newname))
return False
return True
fieldIdList = [fieldHandler0.id]
filepath = "/tmp/test_xmed_saveFields.med"
- print "fieldIdList = %s"%fieldIdList
- print "filepath = %s"%filepath
+ print("fieldIdList = %s"%fieldIdList)
+ print("filepath = %s"%filepath)
dataManager.saveFields(filepath,fieldIdList)
# We just control that the file exists. But we should reload the
# contents to check the fields
import os
if not os.path.exists(filepath):
- print "ERR: the file %s does not exist"%(filepath)
+ print("ERR: the file %s does not exist"%(filepath))
return False
return True
dataManager = factory.getDataManager()
datasourceHandler = dataManager.loadDatasource(testFilePath)
meshHandlerList = dataManager.getMeshList(datasourceHandler.id)
- print meshHandlerList
+ print(meshHandlerList)
if len(meshHandlerList) == 0:
return False
for mRef in meshHandlerList:
meshId = mRef.id
mRes = dataManager.getMesh(meshId)
- print mRes
+ print(mRes)
if ( mRes.name != mRef.name ) or ( mRes.sourceid != mRef.sourceid):
return False
return True
# We look for the fieldseries defined on the first mesh of the list
meshId = meshHandlerList[0].id
fieldseriesList = dataManager.getFieldseriesListOnMesh(meshId)
- print fieldseriesList
+ print(fieldseriesList)
if len(fieldseriesList) == 0:
return False
# i.e. the time steps for this field.
fieldseriesId = fieldseriesList[0].id
fieldList = dataManager.getFieldListInFieldseries(fieldseriesId)
- print fieldList
+ print(fieldList)
if len(fieldList) == 0:
return False
# Try to operate on the two first fields
fieldHandler0 = fieldHandlerList[0]
fieldHandler1 = fieldHandlerList[1]
- print fieldHandler0
- print fieldHandler1
+ print(fieldHandler0)
+ print(fieldHandler1)
calculator = factory.getCalculator()
add = calculator.add(fieldHandler0, fieldHandler1)
- print add
+ print(add)
sub = calculator.sub(fieldHandler0, fieldHandler1)
- print sub
+ print(sub)
mul = calculator.mul(fieldHandler0, fieldHandler1)
- print mul
+ print(mul)
div = calculator.div(fieldHandler0, fieldHandler1)
- print div
+ print(div)
#power = calculator.pow(fieldHandler0, 2)
- #print power
+ # print(power)
linear = calculator.lin(fieldHandler0, 3,2)
- print linear
+ print(linear)
return True
import MEDCALC
nbResultingComponent = MEDCALC.NBCOMP_DEFAULT
res = calculator.fct(fieldHandler,"abs(u)",nbResultingComponent);
- print res
+ print(res)
# In this example, "a" stands for the first component
nbResultingComponent = 1
res = calculator.fct(fieldHandler,"a+2",nbResultingComponent)
- print res
+ print(res)
return True
dataManager.savePersistentFields(filepath)
import os
if not os.path.exists(filepath):
- print "ERR: the file %s does not exist"%(filepath)
+ print("ERR: the file %s does not exist"%(filepath))
return False
return True
import sys, os
if options.imagefile is None:
- print "The image file must be specified"
+ print("The image file must be specified")
sys.exit()
imagefile = options.imagefile
if not os.path.exists(imagefile):
- print "The image file %s does not exists"%imagefile
+ print("The image file %s does not exists"%imagefile)
sys.exit()
if options.medfile is None:
else:
medfile = options.medfile
-print "Convert image file %s to a med field saved in %s"%(imagefile,medfile)
+print("Convert image file %s to a med field saved in %s"%(imagefile,medfile))
from xmedimages import FieldBuilder
builder = FieldBuilder()
builder.image2med(imagefile,medfile)
#ifndef _MED_EVENTLISTENER_I_HXX_
#define _MED_EVENTLISTENER_I_HXX_
+#include <Python.h>
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(MEDEventListener)
#include "SALOME_GenericObj_i.hh"
#ifndef _MED_MODULE_HXX_
#define _MED_MODULE_HXX_
+#include <Python.h>
#include "MEDCALCGUI.hxx"
#include <SalomeApp_Module.h>
#ifndef SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_
#define SRC_MEDCALC_GUI_MEDWIDGETHELPER_HXX_
+#include <Python.h>
#include "WidgetPresentationParameters.hxx"
#include "PresentationEvent.hxx"
#ifndef PRESENTATION_CONTROLLER_HXX
#define PRESENTATION_CONTROLLER_HXX
+#include "MEDEventListener_i.hxx"
+
#include <QObject>
#include "MEDCALCGUI.hxx"
-#include "MEDEventListener_i.hxx"
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(MEDPresentationManager)
#include CORBA_CLIENT_HEADER(MEDDataManager)
#ifndef PROCESSING_CONTROLLER_HXX
#define PROCESSING_CONTROLLER_HXX
+#include <Python.h>
#include "MEDCALCGUI.hxx"
#include "MEDEventListener_i.hxx"
.arg(fieldHandler->type)
.arg(fieldHandler->iteration);
*/
- commands += "print 'Not implemented yet'";
+ commands += "print('Not implemented yet')";
_consoleDriver->exec(commands);
}
// generate the scalar map on this field.
QStringList commands;
//commands+=QString("view(accessField(%1))").arg(fieldHandler->id);
- commands += "print 'Not implemented yet'";
+ commands += "print('Not implemented yet')";
_consoleDriver->exec(commands);
}
#ifndef _WORKSPACE_CONTROLLER_HXX
#define _WORKSPACE_CONTROLLER_HXX
-#include "TreeGuiManager.hxx"
#include "MEDEventListener_i.hxx"
+#include "TreeGuiManager.hxx"
#include "XmedConsoleDriver.hxx"
#include "DatasourceController.hxx"
#include "PresentationController.hxx"
//
// Author : Guillaume Boulant (EDF)
+#include "MEDModule.hxx"
#include "XmedConsoleDriver.hxx"
#include "Utils_SALOME_Exception.hxx"
-#include "MEDModule.hxx"
#include "MEDCommandsHistoryManager_i.hxx"
#include "MEDFactoryClient.hxx"
#include CORBA_CLIENT_HEADER(MED_Gen)
base_pth = os.path.join(GetBaselineDirGUI(), basename)
gen_path = os.path.join(self._tmpDir, basename)
- print base_pth, gen_path
+ print(base_pth, gen_path)
try:
ret = filecmp.cmp(base_pth, gen_path, shallow=False)
except OSError:
presentation_id = medcalc.MakeContour(accessField(55), MEDCALC.VIEW_MODE_REPLACE, colorMap=MEDCALC.COLOR_MAP_BLUE_TO_RED_RAINBOW)
sys.exit(-1);
except:
- print "Contour failed as expected."
+ print("Contour failed as expected.")
sleep(1)
# This functions are to be used to notify the USER of some events
# arising on the field operation. It is NOT to be used for logging
# purpose
-def inf(msg): print "INF: "+str(msg)
-def wrn(msg): print "WRN: "+str(msg)
-def err(msg): print "ERR: "+str(msg)
-def dbg(msg): print "DBG: "+str(msg)
+def inf(msg): print("INF: "+str(msg))
+def wrn(msg): print("WRN: "+str(msg))
+def err(msg): print("ERR: "+str(msg))
+def dbg(msg): print("DBG: "+str(msg))
# Initialize CORBA stuff
-import medcorba
+from . import medcorba
# Connect event listener
-import medevents
+from . import medevents
# Fields utilities
-from fieldproxy import newFieldProxy, FieldProxy
+from .fieldproxy import newFieldProxy, FieldProxy
# Input/Output
-from medio import LoadDataSource
-from medio import LoadImageAsDataSource
-from medio import GetFirstMeshFromDataSource
-from medio import GetFirstFieldFromMesh
+from .medio import LoadDataSource
+from .medio import LoadImageAsDataSource
+from .medio import GetFirstMeshFromDataSource
+from .medio import GetFirstFieldFromMesh
# Presentations
-from medpresentation import MakeMeshView
-from medpresentation import MakeScalarMap
-from medpresentation import MakeContour
-from medpresentation import MakeVectorField
-from medpresentation import MakeSlices
-from medpresentation import MakePointSprite
-from medpresentation import RemovePresentation
-from medpresentation import MakeDeflectionShape
+from .medpresentation import MakeMeshView
+from .medpresentation import MakeScalarMap
+from .medpresentation import MakeContour
+from .medpresentation import MakeVectorField
+from .medpresentation import MakeSlices
+from .medpresentation import MakePointSprite
+from .medpresentation import RemovePresentation
+from .medpresentation import MakeDeflectionShape
-from medpresentation import GetMeshViewParameters
-from medpresentation import GetScalarMapParameters
-from medpresentation import GetContourParameters
-from medpresentation import GetSlicesParameters
-from medpresentation import GetPointSpriteParameters
-from medpresentation import GetVectorFieldParameters
-from medpresentation import GetDeflectionShapeParameters
+from .medpresentation import GetMeshViewParameters
+from .medpresentation import GetScalarMapParameters
+from .medpresentation import GetContourParameters
+from .medpresentation import GetSlicesParameters
+from .medpresentation import GetPointSpriteParameters
+from .medpresentation import GetVectorFieldParameters
+from .medpresentation import GetDeflectionShapeParameters
-from medpresentation import UpdateMeshView
-from medpresentation import UpdateScalarMap
-from medpresentation import UpdateContour
-from medpresentation import UpdateSlices
-from medpresentation import UpdateVectorField
-from medpresentation import UpdatePointSprite
-from medpresentation import UpdateDeflectionShape
+from .medpresentation import UpdateMeshView
+from .medpresentation import UpdateScalarMap
+from .medpresentation import UpdateContour
+from .medpresentation import UpdateSlices
+from .medpresentation import UpdateVectorField
+from .medpresentation import UpdatePointSprite
+from .medpresentation import UpdateDeflectionShape
-from medpresentation import ComputeCellAverageSize, GetDomainCenter, GetSliceOrigins, SelectSourceField
+from .medpresentation import ComputeCellAverageSize, GetDomainCenter, GetSliceOrigins, SelectSourceField
# Processing
-from medprocessing import ChangeUnderlyingMesh
-from medprocessing import InterpolateField
+from .medprocessing import ChangeUnderlyingMesh
+from .medprocessing import InterpolateField
# Console commands
-import medconsole
+from . import medconsole
# Playing test scenarii
-from medtest import PlayQtTestingScenario
-from medtest import RequestSALOMETermination
+from .medtest import PlayQtTestingScenario
+from .medtest import RequestSALOMETermination
# 3 = ON_GAUSS_NE
try:
return __mapTypeOfFieldLabel[typeOfField]
- except IndexError, e:
+ except IndexError as e:
return "UNKNOWN"
#
"""
self.__fieldHandler = fieldHandler
self.__restriction = None
- print self.__repr__()
+ print(self.__repr__())
#
def __getattr__(self, name ):
"""
handler. Only some attributes are writable. The list is
specified in the PROXY_ATTRIBUTES_MAP table.
"""
- if name in PROXY_ATTRIBUTES_MAP.keys():
+ if name in list(PROXY_ATTRIBUTES_MAP.keys()):
if PROXY_ATTRIBUTES_MAP[name] is not None:
medcalc.wrn("The modification of this attribute can't be done that way")
msg="Use f.update(%s=\"%s\") instead to ensure synchronisation of data."
#
def __str__(self):
"""
- This is what is displayed when you type 'print myField'. Note
+ This is what is displayed when you type 'print(myField)'. Note
that this function prints the values of the field and then you
must be aware that a huge amount of data could be
displayed. Moreover, it means that this operation triggers the
offset = operande
medcalc.inf("Application of the offset %s to %s" % (offset, self.fieldname))
rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
offset = -operande
medcalc.inf("Application of the offset %s to %s" % (offset, self.fieldname))
rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
medcalc.inf("Linear transformation %s%s*%s" % (offset, factor, self.fieldname))
try:
rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
offset = 0
medcalc.inf("Scaling %s by factor %s" % (self.fieldname, factor))
rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
offset = 0
medcalc.inf("Scaling %s by factor 1/%s" % (self.fieldname, operande))
rfieldHandler = calculator.lin(self.__fieldHandler, factor, offset)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
nbResComp = MEDCALC.NBCOMP_DEFAULT
try:
rfieldHandler = calculator.fct(self.__fieldHandler,function,nbResComp)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
medcalc.inf("Duplication of %s"%self.fieldname)
try:
rfieldHandler = calculator.dup(self.__fieldHandler)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
rfieldHandler = calculator.fct(self.__fieldHandler,
function,
MEDCALC.NBCOMP_DEFAULT)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
return None
notifyGui_updateField(self.id)
# Print for visual control
- print self.__repr__()
+ print(self.__repr__())
#
#
#
def TEST_typeOfFieldLabel():
- print typeOfFieldLabel(0)
- print typeOfFieldLabel(5)
+ print(typeOfFieldLabel(0))
+ print(typeOfFieldLabel(5))
#
# ===================================================================
"""
try:
dataManager.savePersistentFields(filename)
- except SALOME.SALOME_Exception, ex:
+ except SALOME.SALOME_Exception as ex:
medcalc.err(ex.details.text)
#
# Clean workspace
-from medevents import notifyGui_cleanWorkspace
+from .medevents import notifyGui_cleanWorkspace
def cleanWorkspace():
dvars = pyConsoleGlobals
if dvars is None:
return
all_keys = []
- for varkey, var in dvars.items():
+ for varkey, var in list(dvars.items()):
if isinstance(var, medcalc.FieldProxy):
all_keys.append("%s"%varkey)
if len(all_keys) > 0:
- exec "del "+",".join(all_keys) in pyConsoleGlobals
+ exec("del "+",".join(all_keys), pyConsoleGlobals)
notifyGui_cleanWorkspace()
#
# Remove variable from console
-from medevents import notifyGui_removeFromWorkspace
+from .medevents import notifyGui_removeFromWorkspace
def removeFromWorkspace(fieldProxy):
dvars = pyConsoleGlobals
if dvars is None:
return
- for varkey, var in dvars.items():
+ for varkey, var in list(dvars.items()):
if isinstance(var, medcalc.FieldProxy) and var.id == fieldProxy.id:
- exec("del %s"%varkey) in pyConsoleGlobals
+ exec(("del %s"%varkey), pyConsoleGlobals)
notifyGui_removeFromWorkspace(fieldProxy.id)
#
medcalc.inf("Type this command \"import medcalc; medcalc.setConsoleGlobals(globals())")
if remote is True:
status="========= Fields used in the current context ===\n"
- for varkey in dvars.keys():
+ for varkey in list(dvars.keys()):
var = dvars[varkey]
if isinstance(var, medcalc.FieldProxy):
status+="%s \t(id=%s, name=%s)\n"%(varkey,var.id,var.fieldname)
#
# For simpler typing, one can create a python command for status
-# (avoid to type "print getEnvironment()")
+# (avoid to type "print(getEnvironment())")
class ListFields(object):
"""
A stat object displays the status of the med operating context, i.e. the
#
# Add variable to workspace
-from medevents import notifyGui_putInWorkspace
+from .medevents import notifyGui_putInWorkspace
def putInWorkspace(fieldProxy):
"""
This function puts a reference to this field in the GUI data
try:
eventListenerIOR = dataManager.getEventListenerIOR()
__eventListener = salome.orb.string_to_object(eventListenerIOR)
- except SALOME.SALOME_Exception, e:
+ except SALOME.SALOME_Exception as e:
medcalc.wrn("The event listener is not running yet")
msg ="When you'll have loaded the MED GUI, "
msg+="call explicitely \"medcalc.medevents.connectEventListener()\" "
msg+="to connect the GUI event listener"
medcalc.inf(msg)
__eventListener = None
- except Exception, e:
+ except Exception as e:
medcalc.err("An unknown error occurs. Check if this ior=%s is valid."%eventListenerIOR)
- print e
+ print(e)
#
def eventListenerIsRunning():
coordsY.setValues(arrY,nbNodesY,1)
cmesh.setCoords(coordsX,coordsY)
- print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension()
+ print("Imagem mesh dimension: %d"%cmesh.getSpaceDimension())
# WARN: In the current state of development of MEDLoader, only
# unstructured meshes are supported for writting function in med
medfilename = temp.name
temp.close()
- from medimages import FieldBuilder
+ from .medimages import FieldBuilder
builder = FieldBuilder()
builder.image2med(filename, medfilename)
return LoadDataSource(medfilename)
import medcalc
import MEDCALC, SALOME
from medcalc.medevents import notifyGui_addPresentation, notifyGui_removePresentation, notifyGui_error, notifyGui_modifyPresentation
+from functools import reduce
__manager = medcalc.medcorba.factory.getPresentationManager()
#
def __GetGENERICParameters(tag, presentation_id):
- exec "params = __manager.get%sParameters(presentation_id)" % tag
+ exec("params = __manager.get%sParameters(presentation_id)" % tag)
return params
GetMeshViewParameters = lambda pres_id: __GetGENERICParameters("MeshView", pres_id)
def __UpdateGENERIC(tag, presentation_id, params):
- exec "__manager.update%s(presentation_id, params)" % tag
+ exec("__manager.update%s(presentation_id, params)" % tag)
notifyGui_modifyPresentation(presentation_id)
UpdateMeshView = lambda pres_id, params: __UpdateGENERIC("MeshView", pres_id, params)
@return the average cell size
"""
bb, nCells = obj.GetDataInformation().GetBounds(), obj.GetDataInformation().GetNumberOfCells()
- bb = zip(bb[::2], bb[1::2])
+ bb = list(zip(bb[::2], bb[1::2]))
deltas = [x[1]-x[0] for x in bb]
## Filter out null dimensions:
avgDelta = sum(deltas) / 3.0
@return the center of the domain as the central point of the bounding box
"""
bb = obj.GetDataInformation().GetBounds()
- bb = zip(bb[::2], bb[1::2])
+ bb = list(zip(bb[::2], bb[1::2]))
mids = [x[0] + 0.5*(x[1]-x[0]) for x in bb]
return mids
"""
from math import sqrt
bb = obj.GetDataInformation().GetBounds()
- bb = zip(bb[::2], bb[1::2])
+ bb = list(zip(bb[::2], bb[1::2]))
origin = [x[0] + 0.5*(x[1]-x[0]) for x in bb]
deltas = [x[1]-x[0] for x in bb]
# Compute extent of slices:
if(!PySlice_Check(obj))
throw INTERP_KERNEL::Exception(msg);
Py_ssize_t strt,stp,step;
- PySliceObject *oC=reinterpret_cast<PySliceObject *>(obj);
- PySlice_GetIndices(oC,std::numeric_limits<int>::max(),&strt,&stp,&step);
+ PySlice_GetIndices(obj,std::numeric_limits<int>::max(),&strt,&stp,&step);
if(strt!=0 || stp!=std::numeric_limits<int>::max() || step!=1)
throw INTERP_KERNEL::Exception(msg);
tr.setAll(); pr.setAll(); cr.setAll();
convertPyObjToRS2(obj2,cr,"for 3rd tuple element for components of field");
}
MCAuto<MEDCalculatorDBFieldReal> ret=self->operator()(tr,pr,cr);
- if(PyInt_Check(val))
+ if(PyLong_Check(val))
{
- (*ret)=double(PyInt_AS_LONG(val));
+ (*ret)=double(PyLong_AS_LONG(val));
ret->incrRef();
return ret;
}
Power=MEDCalculatorDBFieldReal(f)
v=Power.getValues()
self.assertEqual(10,len(v));
- for i in xrange(10):
+ for i in range(10):
v1=v[i]
self.assertEqual(35,len(v1))
l=0
- for j in xrange(5):
- for k in xrange(7):
+ for j in range(5):
+ for k in range(7):
self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+1,v1[l],12);
l+=1
pass
p1=Power[2:4,:,:]
v=p1.getValues()
self.assertEqual(2,len(v));
- for i in xrange(2):
+ for i in range(2):
v1=v[i]
self.assertEqual(35,len(v1))
l=0
- for j in xrange(5):
- for k in xrange(7):
+ for j in range(5):
+ for k in range(7):
self.assertAlmostEqual((i+3)*100.+(j+1)*10.+k+1,v1[l],12);
l+=1
pass
p2=Power[3:7,:,2:5]
v=p2.getValues()
self.assertEqual(4,len(v));
- for i in xrange(4):
+ for i in range(4):
v1=v[i]
self.assertEqual(15,len(v1))
l=0
- for j in xrange(5):
- for k in xrange(3):
+ for j in range(5):
+ for k in range(3):
self.assertAlmostEqual((i+4)*100.+(j+1)*10.+k+3,v1[l],12);
l+=1
pass
v=p3.getValues()
self.assertEqual(4,len(v));
expected=[[162192.0, 178952.0, 196112.0, 213672.0, 231632.0], [347792.0, 368552.0, 389712.0, 411272.0, 433232.0], [573392.0, 598152.0, 623312.0, 648872.0, 674832.0], [838992.0, 867752.0, 896912.0, 926472.0, 956432.0]]
- for i in xrange(4):
+ for i in range(4):
v1=v[i]
self.assertEqual(5,len(v1))
l=0
- for j in xrange(5):
+ for j in range(5):
self.assertAlmostEqual(expected[i][j],v1[l],8);
l+=1
pass
Power[:,:,2:4]=7.
v=Power.getValues()
self.assertEqual(10,len(v));
- for i in xrange(10):
+ for i in range(10):
v1=v[i]
self.assertEqual(35,len(v1))
l=0
- for j in xrange(5):
- for k in xrange(2):
+ for j in range(5):
+ for k in range(2):
self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+1,v1[l],12);
l+=1
pass
l+=1
self.assertAlmostEqual(7.,v1[l],12);
l+=1
- for k in xrange(3):
+ for k in range(3):
self.assertAlmostEqual((i+1)*100.+(j+1)*10.+k+5,v1[l],12);
l+=1
pass
Power[1:5,:,3]=p3
v=Power[1:5,:,:].getValues()
self.assertEqual(4,len(v));
- for i in xrange(4):
+ for i in range(4):
v1=v[i]
self.assertEqual(35,len(v1))
l=0
- for j in xrange(5):
- for k in xrange(2):
+ for j in range(5):
+ for k in range(2):
self.assertAlmostEqual((i+2)*100.+(j+1)*10.+k+1,v1[l],12);
l+=1
pass
l+=1
self.assertAlmostEqual(expected[i][j],v1[l],8);
l+=1
- for k in xrange(3):
+ for k in range(3):
self.assertAlmostEqual((i+2)*100.+(j+1)*10.+k+5,v1[l],12);
l+=1
pass
void convertPyObjToRS(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& rs)
{
- if(PyInt_Check(o))
+ if(PyLong_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
rs=val;
return ;
}
void convertPyObjToRS2(PyObject *o, MEDCoupling::MEDCalculatorDBRangeSelection& rs, const char *msg)
{
- if(PyInt_Check(o))
+ if(PyLong_Check(o))
{
- int val=(int)PyInt_AS_LONG(o);
+ int val=(int)PyLong_AS_LONG(o);
rs=val;
return ;
}
throw INTERP_KERNEL::Exception(oss.str().c_str());
}
Py_ssize_t strt,stp,step;
- PySliceObject *oC=reinterpret_cast<PySliceObject *>(o);
- PySlice_GetIndices(oC,std::numeric_limits<int>::max(),&strt,&stp,&step);
+ PySlice_GetIndices(o,std::numeric_limits<int>::max(),&strt,&stp,&step);
rs.setPyStart(strt);
rs.setPyEnd(stp);
}
return false;
if(w.find("del ")!=std::string::npos)
return false;
- const char PRINT[]="print ";
+ const char PRINT[]="print(";
+ const char ENDPRINT[]=")";
bool isPrint=w.find(PRINT)!=std::string::npos;
+ isPrint &= w.find(ENDPRINT)!=std::string::npos;
if(isPrint)
{
std::size_t p=w.find(PRINT);
- w=w.substr(p+sizeof(PRINT)-1);
+ w=w.substr(p+sizeof(PRINT)-sizeof(ENDPRINT)-1);
}
std::string result;
if(!isSPythonExpressionLev1(w,result))
const char SPythonParser::NUMBERS[]="0123456789";
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
+{
+ return _Py_wchar2char(text, error_pos);
+}
+#endif
+
SPythonParser::SPythonParser():_type(EMPTY_TYPE)
{
}
oss << TMPVAR << "=type(" << var << ").__name__";
PyRun_String(oss.str().c_str(),Py_single_input,glob,loc);
PyObject *p=PyDict_GetItemString(glob,TMPVAR);
- const char *type=PyString_AS_STRING(p);
+ const char *type=Py_EncodeLocale(PyUnicode_AS_UNICODE(p), NULL);
std::string typecpp=std::string(type);
if(typecpp=="function")
return FUNC_TYPE;
def f(i):
return i+3
-print f(56.)
+print(f(56.))
Power=0
Power3=Power2
3.6/Power3(0:2,:,2)
-print 2+Power3(0:2,:,:)*4
+print(2+Power3(0:2,:,:)*4)
Power4=Power3.magnitude()
-print Power3.getValues()
+print(Power3.getValues())
Power4.applyFunc("3*x")
Power6=Power(0:2,:,1:4)
Power7=Power(7:9,:,4:)
targetMesh.setName("MyMesh3D");
targetMesh.setDescription("build3DMesh");
targetMesh.allocateCells(12);
- for i in xrange(8):
+ for i in range(8):
targetMesh.insertNextCell(NORM_HEXA8,8,targetConn[8*i:8*(i+1)]);
pass
targetMesh.finishInsertingCells();
f.setGaussLocalizationOnType(NORM_QUAD4,_refCoo2,_gsCoo1,_wg1);
array=DataArrayDouble.New();
ptr=18*2*[None]
- for i in xrange(18*2):
+ for i in range(18*2):
ptr[i]=float(i+1);
pass
array.setValues(ptr,18,2);
f.setDescription("MyDescriptionNE");
array=DataArrayDouble.New();
ptr=18*2*[None]
- for i in xrange(18*2):
+ for i in range(18*2):
ptr[i]=float(i+7)
array.setValues(ptr,18,2);
array.setInfoOnComponent(0,"Power [MW]");
ior=f.read()
f=MEDCouplingCorbaSwigTest.testField()
fCorbaIOR=orb.string_to_object(ior)
-print fCorbaIOR
+print(fCorbaIOR)
for i in range(50):
fCpy=MEDCouplingFieldDoubleClient.New(fCorbaIOR)
- print fCpy.isEqual(f,1e-12,1e-12)
+ print(fCpy.isEqual(f,1e-12,1e-12))
pass
fCorbaIOR.UnRegister()
mCorbaIOR=orb.string_to_object(ior)
for i in range(50):
mCpy=MEDCouplingUMeshClient.New(mCorbaIOR)
- print mCpy.isEqual(m,1e-12)
+ print(mCpy.isEqual(m,1e-12))
pass
mCorbaIOR.UnRegister()
pass
def testMultiFetchingToTestMemoryManagement(self):
- for i in xrange(1000):
+ for i in range(1000):
meshPtr=self._objC.get2DMesh();
_mesh_from_distant=MEDCouplingUMeshClient.New(meshPtr);
meshPtr.UnRegister();
li=8*[None]
th=8*[None]
fieldPtr=self._objC.getFieldScalarOn2DNT();
- for i in xrange(8):
+ for i in range(8):
th[i]=threading.Thread(None,self.corbaField2DNTMFMTThread,"Test"+str(i),(i,fieldPtr,li))
th[i].start()
pass
- for i in xrange(8):
+ for i in range(8):
th[i].join()
pass
- for i in xrange(8-1):
+ for i in range(8-1):
self.assertTrue(li[i].isEqual(li[i+1],1.e-12,1.e-15));
pass
fieldPtr.UnRegister()
ts=fotc.getTimeSteps();
self.assertEqual(6,len(ts));
expected=[0.2,0.7,1.2,1.35,1.7,2.7];
- for i in xrange(6):
+ for i in range(6):
self.assertAlmostEqual(expected[i],ts[i],12);
pass