==========================================
Gestion de configuration du composant MEDCalc
--------------------------------------------
+---------------------------------------------
Le composant logiciel MEDCalc est un package du module SALOME MED,
hébergé dans l'espace source au niveau du sous-répertoire
module SALOME MED.
Organisation des sources du composant MEDCalc
--------------------------------------------
+---------------------------------------------
Le répertoire source `src/MEDCalc` distingue les sous-répertoires
suivants:
MEDCalc framework
Construction du composant MEDCalc
--------------------------------
+---------------------------------
Intégré à la construction du module MED. Le composant MEDCalc dépend de
MEDCoupling et MEDLoader uniquement.
Exécution des tests unitaires du composant MEDCalc
-------------------------------------------------
+--------------------------------------------------
Les tests unitaires peuvent être exécutés au moyen de scripts python
lancés depuis une session shell SALOME. Dans un nouveau shell, taper::
Par exemple, la formule ``W=OP(U,V)`` indique que le champ W est formé
à partir des champs U et V en arguments d'une fonction OP. Dans le cas
d'une opération algébrique comme l'addition (cf. :ref:`Spécification
-des opérations<xmed-specifications>`, le résultat attendu par défaut
+des opérations<xmed-specifications-fr>`, le résultat attendu par défaut
est que pour chaque instant t, chaque position p et chaque composante
c, on a ``W(t,p,c)=U(t,p,c)+V(t,p,c)`` (que l'on peut noter également
``W(:,:,:)=U(:,:,:)+V(:,:,:)`` compte-tenu de la convention présentée
tableaux de valeurs sauvegardés dans un fichier texte ou exporté
sous forme de tableau numpy
-.. _xmed-specifications:
+.. _xmed-specifications-fr:
Spécification des opérations
============================
.. BUG: plantage à l'utilsation dans XMED d'un fichier rechargé
.. (invalid mesh on field)
-.. _xmed.userguide.exemple3:
+.. _xmed.userguide.exemple3-fr:
Exemple 3: Appliquer une opération mathématique sur des champs
--------------------------------------------------------------
Elle peut également être utilisée comme argument des commandes de
gestion disponibles dans l'interface textuelle (dont la liste
détaillée est décrite à la section :ref:`Documentation de l'interface
-textuelle<xmed.userguide.tui>`). Par exemple, la fonction ``view``
+textuelle<xmed.userguide.tui-fr>`). Par exemple, la fonction ``view``
permet d'afficher la carte scalaire du champ dans le viewer::
>>> view(f3)
différents. Pour traiter ce cas de figure, la bibliothèque MEDCoupling
prévoit une fonction de "Changement du maillage support", dont
l'utilisation au niveau du module de manipulation de champs est
-illustrée dans :ref:`l'exemple 4<xmed.userguide.exemple4>` ci-après.
+illustrée dans :ref:`l'exemple 4<xmed.userguide.exemple4-fr>` ci-après.
-.. _xmed.userguide.exemple4:
+.. _xmed.userguide.exemple4-fr:
Exemple 4: Comparer des champs issues de différentes sources
------------------------------------------------------------
Or, les fonctions de manipulation de champs ne permettent pas les
opérations sur des champs dont les maillages supports sont différents
(voir la remarque à la fin de :ref:`l'exemple
-3<xmed.userguide.exemple3>`).
+3<xmed.userguide.exemple3-fr>`).
Pour résoudre ce cas de figure, le module de manipulation de champs
met à disposition la fonction "Change underlying mesh" qui permet de
``parametric_01.med`` et ``f2`` le champ issu du datasource
``parametric_02.med`` par la procédure décrite ci-dessus, alors la
comparaison des deux grandeurs peut être faite comme pour le cas de
-:ref:`l'exemple 3<xmed.userguide.exemple3>`::
+:ref:`l'exemple 3<xmed.userguide.exemple3-fr>`::
>>> r=f1-f2
>>> view(r)
chargeant le fichier généré dans le module PARAVIS pour
visualisation.
-.. _xmed.userguide.tui:
+.. _xmed.userguide.tui-fr:
Utilisation de l'interface textuelle du module MED (TUI)
========================================================
Ces classes proxy sont conçues pour être le lieu d'implémentation de
l'interprétation des commandes utilisateur et donc de l'ergonomie
de manipulation des champs au niveau l'interface textuelle. Ce point
-est développé :ref:`plus bas <develguide_execFieldOperation>`.
+est développé :ref:`plus bas <develguide_execFieldOperation-fr>`.
Programmation de l'interface textuelle
--------------------------------------
.. |IMG_SELECT| image:: ../images/medop-gui-selectfield_scale.png
.. |IMG_ALIAS| image:: ../images/medop-gui-aliasfield_scale.png
-+---------------+---------------+
-| |IMG_SELECT| | |IMG_ALIAS| |
-+---------------+---------------+
++--------------+-------------+
+| |IMG_SELECT| | |IMG_ALIAS| |
++--------------+-------------+
L'image de gauche montre la sélection du pas de temps, l'image de
droite la boîte de dialogue qui permet la saisie de l'alias avec
``SALOME_MED::MEDOP`` créé sur demande par le servant
``SALOME_MED::MED``, voir la fonction ``getFieldFromMed(...)``).
-.. _develguide_execFieldOperation:
+.. _develguide_execFieldOperation-fr:
Exécution des opérations sur le champs
--------------------------------------
.. |IMG_VISU| image:: ../images/medop-gui-visufield_scale.png
.. |IMG_RESULT| image:: ../images/medop-gui-result_scale.png
-+---------------+---------------+
-| |IMG_VISU| | |IMG_RESULT| |
-+---------------+---------------+
++------------+--------------+
+| |IMG_VISU| | |IMG_RESULT| |
++------------+--------------+
Cette fonction répond au besoin de contrôle interactif des résultats
produits par les opérations de manipulation de champs.
import VISU
visuComp = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
- visuComp.SetCurrentStudy(salome.myStudy)
# Then we can import the specified field in the VISU module. This
# creates an study entry in the VISU folder.
pour éviter de passer un pointeur tout en évitant la récopie des
données de la variable.
-.. _xmed-medmem_corbainterface:
+.. _xmed-medmem_corbainterface-fr:
L'interface CORBA SALOME_MED
============================
# Get the VISU component
import VISU
visuComp = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
- visuComp.SetCurrentStudy(salome.myStudy)
# Get the sobject associated to the med object named "Med"
aSObject = salome.myStudy.FindObject("Med")
==========================================
Gestion de configuration du composant MEDCalc
--------------------------------------------
+---------------------------------------------
Le composant logiciel MEDCalc est un package du module SALOME MED,
hébergé dans l'espace source au niveau du sous-répertoire
module SALOME MED.
Organisation des sources du composant MEDCalc
--------------------------------------------
+---------------------------------------------
Le répertoire source `src/MEDCalc` distingue les sous-répertoires
suivants:
MEDCalc framework
Construction du composant MEDCalc
--------------------------------
+---------------------------------
Intégré à la construction du module MED. Le composant MEDCalc dépend de
MEDCoupling et MEDLoader uniquement.
Exécution des tests unitaires du composant MEDCalc
-------------------------------------------------
+--------------------------------------------------
Les tests unitaires peuvent être exécutés au moyen de scripts python
lancés depuis une session shell SALOME. Dans un nouveau shell, taper::
difference ``f3-f4``, then producing a scalar map preview using the
function ``view``::
- >>> view(f3-f4)
+ >>> view(f3-f4)
Finally the field data can be displayed using the command``print``::
All operations driven through GUI can be done (more or less easily) using TUI.
The field manipulation module can even be used exclusively in textual mode.
-..
- For this run the command::
+
+For this run the command:
$ <path/to/appli>/medop.sh
-..
- This command opens a command console ``medop>``. A med file can be loaded and
- manipulated, for example to create fields from file data.
+
+This command opens a command console ``medop>``. A med file can be loaded and
+manipulated, for example to create fields from file data.
Whatever textual or graphical mode is used, a typical workflow in console
looks like the following instructions::
import VISU
visuComp = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
- visuComp.SetCurrentStudy(salome.myStudy)
# Then we can import the specified field in the VISU module. This
# creates an study entry in the VISU folder.
# Get the VISU component
import VISU
visuComp = salome.lcc.FindOrLoadComponent("FactoryServer", "VISU")
- visuComp.SetCurrentStudy(salome.myStudy)
# Get the sobject associated to the med object named "Med"
aSObject = salome.myStudy.FindObject("Med")
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
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))
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# 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__":
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
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(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)
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
"""
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()
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2011-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
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
# defines some parameters
-class Function(object):
+class Function:
def __init__(self, sizeX, sizeY, param):
self.sizeX = sizeX
self.sizeY = sizeY
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):
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2011-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# as a field in a med file.
# (gboulant - 27/06/2011)
+import os
+
import MEDCoupling as MC
import MEDLoader as ML
#image = scipy.lena()
# We could either read a real image using the PIL python package.
from scipy.misc import pilutil
-image = pilutil.imread("images/avatar.png",True)
+CURDIR = os.path.dirname(__file__)
+image = pilutil.imread(os.path.join(CURDIR, "images", "avatar.png"),True)
#from PIL import Image
#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 writing function in med
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2011-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
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 writing 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 writing function in med
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# 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.
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
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)
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# 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 fieldTree:
+ print("%s"%meshName)
+ for fieldName in fieldTree[meshName]:
+ print(" %s"%fieldName)
+ for fieldType in fieldTree[meshName][fieldName]:
+ print(" %s"%fieldType)
+ for itNumber in fieldTree[meshName][fieldName][fieldType]:
+ for itOrder in fieldTree[meshName][fieldName][fieldType][itNumber]:
+ 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)
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2012-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
interface
MED_Gen : Engines::EngineComponent
{
- status addDatasourceToStudy(in SALOMEDS::Study study,
- in MEDCALC::DatasourceHandler datasourceHandler)
+ status addDatasourceToStudy(in MEDCALC::DatasourceHandler datasourceHandler)
raises (SALOME::SALOME_Exception);
- status registerPresentationField(in SALOMEDS::Study study,
- in long fieldId,
- in string name,
- in string type,
- in string ico,
- in long presentationId)
+ status registerPresentationField(in long fieldId,
+ in string name,
+ in string type,
+ in string ico,
+ in long presentationId)
raises (SALOME::SALOME_Exception);
- status registerPresentationMesh(in SALOMEDS::Study study,
- in long meshId,
+ status registerPresentationMesh(in long meshId,
in string name,
in string type,
in string ico,
in long presentationId)
raises (SALOME::SALOME_Exception);
- status unregisterPresentation(in SALOMEDS::Study study,
- in long presentationId)
+ status unregisterPresentation(in long presentationId)
raises (SALOME::SALOME_Exception);
-// PresentationsList getSiblingPresentations(in SALOMEDS::Study study,
-// in long presentationId)
+// PresentationsList getSiblingPresentations(in long presentationId)
// raises (SALOME::SALOME_Exception);
// Get all presentations in study:
- PresentationsList getStudyPresentations(in SALOMEDS::Study study)
+ PresentationsList getStudyPresentations()
raises (SALOME::SALOME_Exception);
- string getStudyPresentationEntry(in SALOMEDS::Study study,
- in long presentationId)
+ string getStudyPresentationEntry(in long presentationId)
raises (SALOME::SALOME_Exception);
void cleanUp();
<component-author>Guillaume Boulant</component-author>
<component-version>@SALOMEMED_VERSION@</component-version>
<component-comment>Factory of SALOME components for MED Field operations</component-comment>
- <component-multistudy>0</component-multistudy>
</component>
<component>
<component-type>MED</component-type>
<component-version>@SALOMEMED_VERSION@</component-version>
<component-comment>MED component engine</component-comment>
- <component-multistudy>0</component-multistudy>
</component>
</component-list>
#include <SALOME_LifeCycleCORBA.hxx>
#include <SALOME_NamingService.hxx>
#include <SALOME_KernelServices.hxx>
+#include <SALOMEDSImpl_AttributeParameter.hxx>
#include <string>
#include <sstream>
}
MED_ORB::status
-MED::addDatasourceToStudy(SALOMEDS::Study_ptr study,
- const MEDCALC::DatasourceHandler& datasourceHandler)
+MED::addDatasourceToStudy(const MEDCALC::DatasourceHandler& datasourceHandler)
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
// check if reference to study is valid
- if (!CORBA::is_nil(study)) {
+ if (!CORBA::is_nil(aStudy)) {
// get full object path
std::string fullName = CORBA::string_dup(datasourceHandler.name);
// check if the object with the same name is already registered in the study
- SALOMEDS::SObject_var sobj = study->FindObjectByPath(fullName.c_str());
+ SALOMEDS::SObject_var sobj = aStudy->FindObjectByPath(fullName.c_str());
if (CORBA::is_nil(sobj)) {
// object is not registered yet -> register
SALOMEDS::GenericAttribute_var anAttr;
SALOMEDS::AttributeParameter_var aParam;
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
// find MED component; create it if not found
- SALOMEDS::SComponent_var father = study->FindComponent("MED");
+ SALOMEDS::SComponent_var father = aStudy->FindComponent("MED");
if (CORBA::is_nil(father)) {
// create component
father = studyBuilder->NewComponent("MED");
}
MED_ORB::status
-MED::registerPresentationField(SALOMEDS::Study_ptr study,
- CORBA::Long fieldId,
- const char* name,
- const char* type,
- const char* ico,
- CORBA::Long presentationId)
+MED::registerPresentationField(CORBA::Long fieldId,
+ const char* name,
+ const char* type,
+ const char* ico,
+ CORBA::Long presentationId)
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
return MED_ORB::OP_ERROR ;
}
std::string entry = _fieldSeriesEntries[fieldSeriesId];
- SALOMEDS::SObject_var sobject = study->FindObjectID(entry.c_str());
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
+ SALOMEDS::SObject_var sobject = aStudy->FindObjectID(entry.c_str());
SALOMEDS::SObject_ptr soFieldseries = sobject._retn();
if (soFieldseries->IsNull()) {
return MED_ORB::OP_ERROR;
}
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
SALOMEDS::SObject_var soPresentation = studyBuilder->NewObject(soFieldseries);
useCaseBuilder->AppendTo(soPresentation->GetFather(), soPresentation);
}
MED_ORB::status
-MED::registerPresentationMesh(SALOMEDS::Study_ptr study,
- CORBA::Long meshId,
- const char* name,
- const char* type,
- const char* ico,
- CORBA::Long presentationId)
+MED::registerPresentationMesh(CORBA::Long meshId,
+ const char* name,
+ const char* type,
+ const char* ico,
+ CORBA::Long presentationId)
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
return MED_ORB::OP_ERROR ;
}
std::string entry = _meshEntries[meshHandler->id];
- SALOMEDS::SObject_var sobject = study->FindObjectID(entry.c_str());
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
+ SALOMEDS::SObject_var sobject = aStudy->FindObjectID(entry.c_str());
SALOMEDS::SObject_ptr soMesh = sobject._retn();
if (soMesh->IsNull()) {
return MED_ORB::OP_ERROR;
}
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
SALOMEDS::SObject_var soPresentation = studyBuilder->NewObject(soMesh);
useCaseBuilder->AppendTo(soPresentation->GetFather(), soPresentation);
MED_ORB::status
-MED::unregisterPresentation(SALOMEDS::Study_ptr study,
- CORBA::Long presentationId)
+MED::unregisterPresentation(CORBA::Long presentationId)
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
SALOMEDS::GenericAttribute_var anAttribute;
- SALOMEDS::SComponent_var father = study->FindComponent("MED");
- SALOMEDS::ChildIterator_var it = study->NewChildIterator(father);
+ SALOMEDS::SComponent_var father = aStudy->FindComponent("MED");
+ SALOMEDS::ChildIterator_var it = aStudy->NewChildIterator(father);
for (it->InitEx(true); it->More(); it->Next()) {
SALOMEDS::SObject_var child(it->Value());
}
MED_ORB::PresentationsList*
-MED::getStudyPresentations(SALOMEDS::Study_ptr study)
+MED::getStudyPresentations()
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
MED_ORB::PresentationsList* presList = new MED_ORB::PresentationsList;
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
SALOMEDS::GenericAttribute_var anAttribute;
- SALOMEDS::SComponent_var father = study->FindComponent("MED");
- SALOMEDS::ChildIterator_var it = study->NewChildIterator(father);
+ SALOMEDS::SComponent_var father = aStudy->FindComponent("MED");
+ SALOMEDS::ChildIterator_var it = aStudy->NewChildIterator(father);
for (it->InitEx(true); it->More(); it->Next())
{
SALOMEDS::SObject_var child(it->Value());
}
char*
-MED::getStudyPresentationEntry(SALOMEDS::Study_ptr study, CORBA::Long presentationId)
+MED::getStudyPresentationEntry(CORBA::Long presentationId)
{
// set exception handler to catch unexpected CORBA exceptions
Unexpect aCatch(SALOME_SalomeException);
MED_ORB::PresentationsList* presList = new MED_ORB::PresentationsList;
- SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
- SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
+ SALOMEDS::Study_var aStudy = KERNEL::getStudyServant();
+ SALOMEDS::StudyBuilder_var studyBuilder = aStudy->NewBuilder();
+ SALOMEDS::UseCaseBuilder_var useCaseBuilder = aStudy->GetUseCaseBuilder();
SALOMEDS::GenericAttribute_var anAttribute;
- SALOMEDS::SComponent_var father = study->FindComponent("MED");
- SALOMEDS::ChildIterator_var it = study->NewChildIterator(father);
+ SALOMEDS::SComponent_var father = aStudy->FindComponent("MED");
+ SALOMEDS::ChildIterator_var it = aStudy->NewChildIterator(father);
for (it->InitEx(true); it->More(); it->Next())
{
SALOMEDS::SObject_var child(it->Value());
Engines::TMPFile*
-MED::DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+MED::DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript)
{
- SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow(theStudy);
- if(CORBA::is_nil(aStudy)) {
- std::cerr << "Error: Cannot find the study\n";
- return new Engines::TMPFile(0);
- }
-
- SALOMEDS::SObject_var aSO = aStudy->FindComponent("MED");
+ SALOMEDS::SObject_var aSO = KERNEL::getStudyServant()->FindComponent("MED");
if(CORBA::is_nil(aSO)) {
std::cerr << "Error: Cannot find component MED\n";
return new Engines::TMPFile(0);
}
char*
-MED::getObjectInfo(CORBA::Long studyId, const char* entry)
+MED::getObjectInfo(const char* entry)
{
- SALOME_LifeCycleCORBA lcc;
- CORBA::Object_var aSMObject = lcc.namingService()->Resolve( "/myStudyManager" );
- SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow( aSMObject );
- SALOMEDS::Study_var aStudy = aStudyManager->GetStudyByID( studyId );
- SALOMEDS::SObject_var aSObj = aStudy->FindObjectID( entry );
+ SALOMEDS::SObject_var aSObj = KERNEL::getStudyServant()->FindObjectID( entry );
SALOMEDS::SObject_var aResultSObj;
if (aSObj->ReferencedObject(aResultSObj))
aSObj = aResultSObj;
#include CORBA_SERVER_HEADER(MEDDataManager)
#include CORBA_CLIENT_HEADER(SALOMEDS)
#include <SALOME_Component_i.hxx>
-#include <SALOMEDS_Study.hxx>
#include <map>
#include <string>
const char* interfaceName);
virtual ~MED();
- MED_ORB::status addDatasourceToStudy(SALOMEDS::Study_ptr study,
- const MEDCALC::DatasourceHandler& datasourceHandler);
+ MED_ORB::status addDatasourceToStudy(const MEDCALC::DatasourceHandler& datasourceHandler);
- MED_ORB::status registerPresentationField(SALOMEDS::Study_ptr study,
- CORBA::Long fieldId,
- const char* name,
- const char* type,
- const char* ico,
- CORBA::Long presentationId);
+ MED_ORB::status registerPresentationField(CORBA::Long fieldId,
+ const char* name,
+ const char* type,
+ const char* ico,
+ CORBA::Long presentationId);
- MED_ORB::status registerPresentationMesh(SALOMEDS::Study_ptr study,
- CORBA::Long meshId,
- const char* name,
- const char* type,
- const char* ico,
- CORBA::Long presentationId);
+ MED_ORB::status registerPresentationMesh(CORBA::Long meshId,
+ const char* name,
+ const char* type,
+ const char* ico,
+ CORBA::Long presentationId);
- MED_ORB::status unregisterPresentation(SALOMEDS::Study_ptr study,
- CORBA::Long presentationId);
+ MED_ORB::status unregisterPresentation(CORBA::Long presentationId);
// // Caller owns the returned list, and is responsible for the list deletion.
-// MED_ORB::PresentationsList* getSiblingPresentations(SALOMEDS::Study_ptr study,
-// CORBA::Long presentationId);
+// MED_ORB::PresentationsList* getSiblingPresentations(CORBA::Long presentationId);
// Get all presentations registered in the study
- MED_ORB::PresentationsList* getStudyPresentations(SALOMEDS::Study_ptr study);
+ MED_ORB::PresentationsList* getStudyPresentations();
- char* getStudyPresentationEntry(SALOMEDS::Study_ptr study, CORBA::Long presentationId);
+ char* getStudyPresentationEntry(CORBA::Long presentationId);
void cleanUp();
/*! Dump the study as a Python file */
- virtual Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+ virtual Engines::TMPFile* DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript);
// For tooltips
virtual CORBA::Boolean hasObjectInfo();
- virtual char* getObjectInfo(CORBA::Long studyId, const char* entry);
+ virtual char* getObjectInfo(const char* entry);
private:
std::map<long, std::string> _fieldSeriesEntries;
#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");
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
__import__(corbaModule)
factory=salome.lcc.FindOrLoadComponent(containerType,componentName)
# This is not the main CORBA component of the SALOME module MED
-# (i.e. the engine associated to the active study), but the CORBA
+# (i.e. the engine associated to the study), but the CORBA
# entry point for MED fields operations (i.e. a CORBA component
# reachable throughout the LifeCycleCORBA). This entry point is used to
# get the other SALOME CORBA components required for MED field
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
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#!/usr/bin/env python3
# Copyright (C) 2011-2016 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
#
# Author : Guillaume Boulant (EDF)
-from optparse import OptionParser
-parser = OptionParser()
-parser.add_option("-i", "--imagefile", dest="imagefile",
+from argparse import ArgumentParser
+parser = ArgumentParser()
+parser.add_agument("-i", "--imagefile", dest="imagefile",
help="image file to convert", metavar="FILE")
-parser.add_option("-m", "--medfile", dest="medfile", default=None,
+parser.add_agument("-m", "--medfile", dest="medfile", default=None,
help="output med file", metavar="FILE")
-(options, args) = parser.parse_args()
+args = parser.parse_args()
import sys, os
-if options.imagefile is None:
- print "The image file must be specified"
+if args.imagefile is None:
+ print("The image file must be specified")
sys.exit()
-imagefile = options.imagefile
+imagefile = args.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:
+if args.medfile is None:
basename = os.path.basename(imagefile)
medfile = basename[0:len(basename)-3] + "med"
else:
- medfile = options.medfile
+ medfile = args.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)
return;
}
- SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(_salomeModule->application()->activeStudy());
- _PTR(Study) studyDS = study->studyDS();
-
- _salomeModule->engine()->addDatasourceToStudy(_CAST(Study, studyDS)->GetStudy(), *datasourceHandler);
+ _salomeModule->engine()->addDatasourceToStudy(*datasourceHandler);
// update Object browser
_salomeModule->getApp()->updateObjectBrowser(true);
void DatasourceController::OnExpandField()
{
- // We need a studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject)
SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
for (int i=0; i<listOfSObject->size(); i++) {
}
void DatasourceController::OnUseInWorkspace() {
- // We need a studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject)
SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
if ( listOfSObject->size() == 1 ) {
#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"
void
PresentationController::visualize(PresentationEvent::EventType eventType)
{
- // We need a _studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject)
SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
void
PresentationController::onDeletePresentation()
{
- // We need a _studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject)
SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
void
PresentationController::onParavisDump()
{
- // We need a _studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject)
SALOME_StudyEditor::SObjectList* listOfSObject = _studyEditor->getSelectedObjects();
name = tr(name.c_str()).toStdString();
oss << name << " (" << presentationId << ")";
- SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(_salomeModule->application()->activeStudy());
- _PTR(Study) studyDS = study->studyDS();
-
// Mesh views are always registered at the mesh level:
if (type == MEDPresentationMeshView::TYPE_NAME)
{
- _salomeModule->engine()->registerPresentationMesh(_CAST(Study, studyDS)->GetStudy(), dataId,
- oss.str().c_str(), type.c_str(),ico.c_str(), presentationId);
+ _salomeModule->engine()->registerPresentationMesh(dataId, oss.str().c_str(), type.c_str(),ico.c_str(), presentationId);
}
else
- _salomeModule->engine()->registerPresentationField(_CAST(Study, studyDS)->GetStudy(), dataId,
- oss.str().c_str(), type.c_str(),ico.c_str(), presentationId);
+ _salomeModule->engine()->registerPresentationField(dataId, oss.str().c_str(), type.c_str(),ico.c_str(), presentationId);
// update Object browser
_salomeModule->getApp()->updateObjectBrowser(true);
// auto-select new presentation
- std::string entry = _salomeModule->engine()->getStudyPresentationEntry(_CAST(Study, studyDS)->GetStudy(), presentationId);
+ std::string entry = _salomeModule->engine()->getStudyPresentationEntry(presentationId);
SALOME_ListIO selectedObjects;
LightApp_Study* lightStudy = dynamic_cast<LightApp_Study*>( _salomeModule->application()->activeStudy() );
QString component = lightStudy->componentDataType( entry.c_str() );
return;
}
- SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(_salomeModule->application()->activeStudy());
- _PTR(Study) studyDS = study->studyDS();
-
- _salomeModule->engine()->unregisterPresentation(_CAST(Study, studyDS)->GetStudy(), presentationId);
+ _salomeModule->engine()->unregisterPresentation(presentationId);
// update Object browser
_salomeModule->getApp()->updateObjectBrowser(true);
PresentationController::_dealWithReplaceMode()
{
// Deal with replace mode: presentations with invalid IDs have to be removed:
- SalomeApp_Study* study = dynamic_cast<SalomeApp_Study*>(_salomeModule->application()->activeStudy());
- _PTR(Study) studyDS = study->studyDS();
MEDCALC::PresentationsList * lstManager = _presManager->getAllPresentations();
- MED_ORB::PresentationsList * lstModule = _salomeModule->engine()->getStudyPresentations(_CAST(Study, studyDS)->GetStudy());
+ MED_ORB::PresentationsList * lstModule = _salomeModule->engine()->getStudyPresentations();
// The IDs not in the intersection needs deletion:
CORBA::Long * last = lstManager->get_buffer() + lstManager->length();
for (unsigned i = 0; i < lstModule->length(); i++) {
#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)
void
ProcessingController::OnChangeUnderlyingMesh()
{
- // We need a studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject). In case of a
// multiple selection, we consider only the first item. At least one
// item must be selected.
void
ProcessingController::OnInterpolateField()
{
- // We need a studyEditor updated on the active study
- _studyEditor->updateActiveStudy();
-
// Get the selected objects in the study (SObject). In case of a
// multiple selection, we consider only the first item. At least one
// item must be selected.
#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
med_engine = salome.lcc.FindOrLoadComponent(containerType,medComponentName)
factory = salome.lcc.FindOrLoadComponent(containerType,factoryComponentName)
# The factory is not the main CORBA component of the SALOME module MED
-# (i.e. the engine associated to the active study), but the CORBA
+# (i.e. the engine associated to the study), but the CORBA
# entry point for MED fields operations (i.e. a CORBA component
# reachable through the LifeCycleCORBA). This entry point is used to
# get the other SALOME CORBA components required for MED field
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 explicitly \"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 writing 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:
INSTALL(TARGETS medcalculatorspython DESTINATION ${SALOME_INSTALL_LIBS})
SET_SOURCE_FILES_PROPERTIES(MEDCalculator.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(MEDCalculator.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(MEDCalculator.i PROPERTIES SWIG_FLAGS "-py3")
SET(SWIG_MODULE_MEDCalculator_EXTRA_FLAGS "${NUMPY_DEFINITIONS};${SCIPY_DEFINITIONS}")
SWIG_ADD_MODULE(MEDCalculator python MEDCalculator.i)
SWIG_LINK_LIBRARIES(MEDCalculator ${PYTHON_LIBRARIES} medcalculator)
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;
}
%include "MEDCouplingFinalize.i"
%pythoncode %{
+MEDCalculatorDBFieldReal.__rtruediv__ = MEDCalculatorDBFieldReal.__rdiv__
def MEDCouplingMEDFileUMeshReduce(self):
return MEDCouplingStdReduceFunct,(MEDFileUMesh,((),(self.__getstate__()),))
MEDFileUMesh.__reduce__=MEDCouplingMEDFileUMeshReduce
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
#include <limits>
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
+{
+ return _Py_wchar2char(text, error_pos);
+}
+#endif
+
static PyObject* convertMEDCalculatorDBField(MEDCoupling::MEDCalculatorDBField *f, int owner)
{
PyObject *ret=0;
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 ;
}
if(PyString_Check(o))
{
- char *s=PyString_AsString(o);
+ char *s=Py_EncodeLocale(PyUnicode_AS_UNICODE(o), NULL);
rs=s;
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:)
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(MEDCouplingCorba.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(MEDCouplingCorba.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(MEDCouplingCorba.i PROPERTIES SWIG_FLAGS "-py3")
SET(SWIG_MODULE_MEDCouplingCorba_EXTRA_FLAGS "${NUMPY_DEFINITIONS};${SCIPY_DEFINITIONS}")
SET(MEDCouplingCorba_SWIG_DPYS_FILES
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(MEDCouplingClient.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(MEDCouplingClient.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(MEDCouplingClient.i PROPERTIES SWIG_FLAGS "-py3")
SET(SWIG_MODULE_MEDCouplingClient_EXTRA_FLAGS "${NUMPY_DEFINITIONS};${SCIPY_DEFINITIONS}")
INCLUDE_DIRECTORIES(
%nodefaultctor;
%nodefaultdtor;
+%{
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
+{
+ return _Py_wchar2char(text, error_pos);
+}
+#endif
+%}
+
namespace MEDCoupling
{
class MEDCouplingFieldDoubleClient
PyObject *iorField=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",fieldPtr);
if(!iorField)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingFieldDoubleClient.New appears to differ from CORBA reference ! Expecting a FieldDouble CORBA reference !");
- char *ior=PyString_AsString(iorField);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorField), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var fieldPtrCpp=orb->string_to_object(ior);
PyObject *iorField=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",fieldPtr);
if(!iorField)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingFieldTemplateClient.New appears to differ from CORBA reference ! Expecting a FieldTemplate CORBA reference !");
- char *ior=PyString_AsString(iorField);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorField), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var fieldPtrCpp=orb->string_to_object(ior);
PyObject *iorField=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",fieldPtr);
if(!iorField)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingFieldTemplateClient.New appears to differ from CORBA reference ! Expecting a MultiFields CORBA reference !");
- char *ior=PyString_AsString(iorField);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorField), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var fieldPtrCpp=orb->string_to_object(ior);
PyObject *iorField=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",fieldPtr);
if(!iorField)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingFieldOverTimeClient.New appears to differ from CORBA reference ! Expecting a FieldOverTime CORBA reference !");
- char *ior=PyString_AsString(iorField);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorField), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var fieldPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingMeshClient.New appears to differ from CORBA reference ! Expecting a MeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingUMeshClient.New appears to differ from CORBA reference ! Expecting a UMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCoupling1SGTUMeshClient.New appears to differ from CORBA reference ! Expecting a 1SGTUMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCoupling1DGTUMeshClient.New appears to differ from CORBA reference ! Expecting a 1DGTUMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingExtrudedMeshClient.New appears to differ from CORBA reference ! Expecting an ExtrudedMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingCMeshClient.New appears to differ from CORBA reference ! Expecting a CMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingIMeshClient.New appears to differ from CORBA reference ! Expecting a IMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of MEDCouplingCurveLinearMeshClient.New appears to differ from CORBA reference ! Expecting a CurveLinearMeshCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of DataArrayDoubleClient.New appears to differ from CORBA reference ! Expecting a DataArrayDoubleCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
PyObject *iorMesh=PyObject_CallMethod(orbPython,(char*)"object_to_string",(char*)"O",meshPtr);
if(!iorMesh)
throw INTERP_KERNEL::Exception("Error : the input parameter of DataArrayIntClient.New appears to differ from CORBA reference ! Expecting a DataArrayIntCorbaInterface CORBA reference !");
- char *ior=PyString_AsString(iorMesh);
+ char *ior=Py_EncodeLocale(PyUnicode_AS_UNICODE(iorMesh), NULL);
int argc=0;
CORBA::ORB_var orb=CORBA::ORB_init(argc,0);
CORBA::Object_var meshPtrCpp=orb->string_to_object(ior);
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