::
- from MEDCoupling import *
- from MEDLoader import *
- import MEDLoaderDataForTest
-
+ import medcoupling as mc
from math import *
# Definition of environment variables
# => Definition of the mesh dimension
# => Definition of number of cells
# => Definition of name of meshing
- mesh=MEDCouplingUMesh.New()
+ mesh=mc.MEDCouplingUMesh.New()
mesh.setMeshDimension(3)
mesh.allocateCells(nbOfCells+nbOfCells2D)
mesh.setName("3Dcube")
print("4 ********************")
# Adding cells in meshing
for i in range(nbOfCells):
- mesh.insertNextCell(NORM_HEXA8,8,connectivity[8*i:8*(i+1)])
+ mesh.insertNextCell(mc.NORM_HEXA8,8,connectivity[8*i:8*(i+1)])
pass
print("5 ********************")
# Settings of coordinates and verify if it's OK
- myCoords = DataArrayDouble.New()
+ myCoords = mc.DataArrayDouble.New()
myCoords.setValues(coordinates,nbOfNodes,3)
mesh.setCoords(myCoords)
mesh.checkConsistencyLight()
# => Definition of the mesh support
# => Definition of field name
# => Definition of field nature
- field = MEDCouplingFieldDouble.New(ON_CELLS)
+ field = mc.MEDCouplingFieldDouble.New(ON_CELLS)
field.setMesh(mesh)
field.setName("field")
field.setNature(ExtensiveMaximum)
# Computing and setting field values
- myCoords=DataArrayDouble.New()
+ myCoords=mc.DataArrayDouble.New()
sampleTab=[]
bar = mesh.computeCellCenterOfMass()
print(bar.getNbOfElems())
myCoords.setValues(sampleTab,nbOfCells,1)
field.setArray(myCoords)
- fBF = MEDCouplingFieldDouble.New(ON_CELLS)
+ fBF = mc.MEDCouplingFieldDouble.New(ON_CELLS)
fBF.setMesh(mesh2D)
fBF.setName("fieldBottomFace")
fBF.setNature(ExtensiveMaximum)
Cval = 10.
- myCoords2D=DataArrayDouble.New()
+ myCoords2D=mc.DataArrayDouble.New()
sampleTab=[]
for i in range(nbOfCells2D):
sampleTab.append(Cval)
myCoords2D.setValues(sampleTab,nbOfCells2D,1)
fBF.setArray(myCoords2D)
- medFileName = "MEDCoupling_cube3D.med"
+ medFileName = "mc.MEDCoupling_cube3D.med"
# For note : True / False in Write* functions
# => True : overwriting existing file
# => False : add in existing file
meshes=[mesh2D,mesh]
- MEDLoader.WriteUMeshes(medFileName,meshes,True);
- MEDLoader.WriteField(medFileName,field,False)
- MEDLoader.WriteField(medFileName,fBF,False)
+ mc.WriteUMeshes(medFileName,meshes,True);
+ mc.WriteField(medFileName,field,False)
+ mc.WriteField(medFileName,fBF,False)
::
- from MEDCoupling import *
- from MEDLoader import *
- import MEDLoaderDataForTest
-
+ import medcoupling as mc
from math import *
spaceDim3D = 3
coordinates.append(float(i))
coordinates.append(float(j))
Connectivities = [0,4,5,1, 1,5,6,2, 2,6,7,3, 4,8,9,5, 5,9,10,6, 6,10,11,7, 8,12,13,9, 9,13,14,10, 10,14,15,11]
- myCoords = DataArrayDouble.New()
+ myCoords = mc.DataArrayDouble.New()
myCoords.setValues(coordinates,NbNode2D,MeshDim2D)
- m1 = MEDCouplingUMesh.New()
+ m1 = mc.MEDCouplingUMesh.New()
m1.setMeshDimension(MeshDim2D)
m1.allocateCells(NbCell2D)
m1.setCoords(myCoords)
m1.setName("2D_Support")
for i in range(NbCell2D):
- m1.insertNextCell(NORM_QUAD4,4,Connectivities[4*i:4*(i+1)])
+ m1.insertNextCell(mc.NORM_QUAD4,4,Connectivities[4*i:4*(i+1)])
m1.changeSpaceDimension(3)
# Creation of 1D meshing
coords = [ 0.0, 1.0, 2.0, 3.0 ]
conn = [ 0,1, 1,2, 2,3 ]
- m2 = MEDCouplingUMesh.New()
+ m2 = mc.MEDCouplingUMesh.New()
m2.setMeshDimension(1)
m2.allocateCells(3)
- m2.insertNextCell(NORM_SEG2,2,conn[0:2])
- m2.insertNextCell(NORM_SEG2,2,conn[2:4])
- m2.insertNextCell(NORM_SEG2,2,conn[4:6])
- myCoords1D=DataArrayDouble.New()
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[0:2])
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[2:4])
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[4:6])
+ myCoords1D=mc.DataArrayDouble.New()
myCoords1D.setValues(coords,4,1)
m2.setCoords(myCoords1D)
m2.changeSpaceDimension(3)
meshGroup.setName("meshGroup");
medFileName = "MEDCoupling_Extrudedcube3D.med"
- MEDLoader.WriteUMeshesPartition(medFileName,"Extrusion",[m3,meshGroup],True)
+ mc.WriteUMeshesPartition(medFileName,"Extrusion",[m3,meshGroup],True)
::
- from MEDCoupling import *
- from MEDLoader import *
- import MEDLoaderDataForTest
-
+ import medcoupling as mc
from math import *
spaceDim3D = 3
# Creation of a grid => Structured mesh
# Need directions definition
- mesh=MEDCouplingCMesh.New()
- coordsX=DataArrayDouble.New()
+ mesh=mc.MEDCouplingCMesh.New()
+ coordsX=mc.DataArrayDouble.New()
arrX=[ 0., 1., 2., 3. ]
coordsX.setValues(arrX,4,1)
- coordsY=DataArrayDouble.New()
+ coordsY=mc.DataArrayDouble.New()
arrY=[ 0., 1., 2., 3. ]
coordsY.setValues(arrY,4,1)
- coordsZ=DataArrayDouble.New()
+ coordsZ=mc.DataArrayDouble.New()
arrZ=[ 0., 1., 2., 3. ]
coordsZ.setValues(arrZ,4,1)
mesh.setCoords(coordsX,coordsY,coordsZ)
# Definition of the name group
tabIdCells.setName("meshGroup")
- # Passing MEDCoupling to MEDFile
- fmeshU = MEDFileUMesh.New()
+ # Passing mc.MEDCoupling to mc.MEDFile
+ fmeshU = mc.MEDFileUMesh.New()
fmeshU.setName("Grid")
fmeshU.setDescription("IHopeToConvinceLastMEDMEMUsers")
myCoords = meshU.getCoords()
::
- import MEDLoader as ml
+ import medcoupling as mc
import numpy as np
# Get available time steps
- data = ml.MEDFileData("agitateur.med")
+ data = mc.MEDFileData("agitateur.med")
ts = data.getFields()[0].getTimeSteps()
print(ts)
# Get position of the swirler
fMts = data.getFields()["DISTANCE_INTERFACE_ELEM_BODY_ELEM_DOM"]
f1ts = fMts[(2,-1)]
- fMc = f1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ fMc = f1ts.getFieldAtLevel(mc.ON_CELLS,0)
arr = fMc.getArray()
arr.getMinMaxPerComponent() # just to see the field variation range per component
ids = arr.findIdsInRange(0.,1.)
# Extract pression field on the swirler
pressMts = data.getFields()["PRESSION_ELEM_DOM"]
press1ts = pressMts[(2,-1)]
- pressMc = press1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ pressMc = press1ts.getFieldAtLevel(mc.ON_CELLS,0)
pressOnAgitateurMc = pressMc[ids]
#
pressOnAgitateurMc.getMesh().zipCoords()
barySkin=agitateurSkinMc.computeCellCenterOfMass()
posSkin = barySkin-centerOfMass
- torquePerCellOnSkin = ml.DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
+ torquePerCellOnSkin = mc.DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
zeTorque = torquePerCellOnSkin.accumulate()
print("couple = %r N.m" % zeTorque[2])
# Power computation
speedMts = data.getFields()["VITESSE_ELEM_DOM"]
speed1ts = speedMts[(2,-1)]
- speedMc = speed1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ speedMc = speed1ts.getFieldAtLevel(mc.ON_CELLS,0)
speedOnSkin = speedMc.getArray()[tupleIdsInField]
- powerSkin = ml.DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
+ powerSkin = mc.DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
power = powerSkin.accumulate()[0]
print("power = %r W"%(power))
# Eigen vector computation
print(vect0)
def computeAngle(locAgitateur1ts):
- fMc = locAgitateur1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ fMc = locAgitateur1ts.getFieldAtLevel(mc.ON_CELLS,0)
arr = fMc.getArray()
ids = arr.findIdsInRange(0.,1.)
f2Mc = fMc[ids]
::
- import MEDLoader as ml
+ import medcoupling as mc
def displayVTK(m,fname):
tmp = m.deepCopy()
return
# Read and clean Fixe.med
- fixe = ml.MEDFileMesh.New("Fixe.med")
+ fixe = mc.MEDFileMesh.New("Fixe.med")
fixm = fixe.getMeshAtLevel(0)
print("Nb of nodes in the file : %i " % (fixm.getNumberOfNodes()))
fixm.mergeNodes(1e-10)
print("Nb of non duplicated nodes : %i" % (fixm.getNumberOfNodes()))
# Read and clean Mobile.med
- mobile = ml.MEDFileMesh.New("Mobile.med")
+ mobile = mc.MEDFileMesh.New("Mobile.med")
mobm = mobile.getMeshAtLevel(0)
mobm.mergeNodes(1e-10)
# Visualize fixm and mobm with PARAVIEW
partFixm.zipCoords()
displayVTK(partFixm,"partFixm.vtu")
# Intersect partFixm with zone1Mobm
- partFixMob, iPart, iMob = ml.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
+ partFixMob, iPart, iMob = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
partFixMob.mergeNodes(1e-10)
# Get the part of partFixm not included in zone1Mobm using partFixMob
ids3 = iMob.findIdsEqual(-1)
pass
print("Check #2? %s" % (str(isCheck2OK)))
# Indicator field creation
- f = ml.MEDCouplingFieldDouble(ml.ON_CELLS,ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble(mc.ON_CELLS,mc.ONE_TIME)
m = partFixMob.deepCopy()
m.tessellate2D(0.1)
f.setMesh(m)
- arr = ml.DataArrayDouble(partFixMob.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob.getNumberOfCells(),1)
arr[iMob.findIdsEqual(-1)] = 0.
arr[iMob.findIdsNotEqual(-1)] = 1.
f.setArray(arr)
f.checkConsistencyLight()
f.setName("Zone")
- ml.MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
# Other zones
- zonesMobm = ml.MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
+ zonesMobm = mc.MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
zonesMobm.zipCoords()
- partFixMob2,iPart2,iMob2 = ml.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
+ partFixMob2,iPart2,iMob2 = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
partFixMob2.mergeNodes(1e-10)
- f2 = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ f2 = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
m2 = partFixMob2.deepCopy()
m2.tessellate2D(0.1)
f2.setMesh(m2)
- arr = ml.DataArrayDouble(partFixMob2.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob2.getNumberOfCells(),1)
arr[iMob2.findIdsEqual(-1)]=0.
st = 0
end = st + len(zonesInMobm[0])
f2.setArray(arr)
f2.checkConsistencyLight()
f2.setName("Zone2")
- ml.MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
::
- from MEDCoupling import *
- from MEDLoader import *
-
+ import medcoupling as mc
from math import *
numberOfNodes = 25
print("2 ********************")
# Creation of mesh
- mesh=MEDCouplingUMesh.New()
+ mesh=mc.MEDCoupplingUMesh.New()
mesh.setMeshDimension(2)
mesh.allocateCells(numberOfCells)
mesh.setName("MaFleur")
- myCoords=DataArrayDouble.New()
+ myCoords=mc.DataArrayDouble.New()
myCoords.setValues(coordinates,numberOfNodes,2)
mesh.setCoords(myCoords)
connectivity.append(i%6+1)
connectivity.append((i+1)%6+1)
for i in range(6):
- mesh.insertNextCell(NORM_TRI3,3,connectivity[3*i:3*(i+1)])
+ mesh.insertNextCell(mc.NORM_TRI3,3,connectivity[3*i:3*(i+1)])
pass
print("4 ********************")
connectivity.append(start+2*(i+3)+3)
connectivity.append((i+1)%6+1)
for i in range(6):
- mesh.insertNextCell(NORM_POLYGON,6,connectivity[6*i:6*(i+1)])
+ mesh.insertNextCell(mc.NORM_POLYGON,6,connectivity[6*i:6*(i+1)])
pass
print("5 ********************")
mesh.checkConsistencyLight()
- medFileName = "MEDCoupling_Fleur.med"
- MEDLoader.WriteUMesh(medFileName,mesh,True)
+ medFileName = "MEDCouppling_Fleur.med"
+ mc.WriteUMesh(medFileName,mesh,True)
::
- from MEDCoupling import *
- from MEDLoader import *
-
+ import medcoupling as mc
medFileName = "MEDCoupling_cube3D.med"
MeshName = "3Dcube"
Field2DName = "fieldBottomFace"
# Retrieving meshes
- mesh3D = MEDLoader.ReadUMeshFromFile(medFileName,MeshName,0)
- mesh2D = MEDLoader.ReadUMeshFromFile(medFileName,MeshName,-1)
+ mesh3D = mc.ReadUMeshFromFile(medFileName,MeshName,0)
+ mesh2D = mc.ReadUMeshFromFile(medFileName,MeshName,-1)
# Retrieving fields
- f = MEDLoader.ReadFieldCell(medFileName,mesh3D.getName(),0,FieldName,-1,-1)
- f2 = MEDLoader.ReadFieldCell(medFileName,mesh2D.getName(),-1,Field2DName,-1,-1)
+ f = mc.ReadFieldCell(medFileName,mesh3D.getName(),0,FieldName,-1,-1)
+ f2 = mc.ReadFieldCell(medFileName,mesh2D.getName(),-1,Field2DName,-1,-1)
# Retrieving Coords Mesh
Coords3D = mesh3D.getCoords()
::
- import MEDLoader as ml
+ import medcoupling as mc
# Mesh creation
targetCoords = [-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn = [0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh = ml.MEDCouplingUMesh("MyMesh",2)
+ targetMesh = mc.MEDCouplingUMesh("MyMesh",2)
targetMesh.allocateCells(5)
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[4:7])
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[7:10])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[0:4])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[10:14])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[14:18])
- myCoords = ml.DataArrayDouble(targetCoords,9,2)
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
+ myCoords = mc.DataArrayDouble(targetCoords,9,2)
myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
targetMesh.setCoords(myCoords)
# Build the 2D faces from the 3D volumes (descending connectivity)
#
# Meshes
#
- meshMEDFile = ml.MEDFileUMesh()
+ meshMEDFile = mc.MEDFileUMesh()
meshMEDFile.setMeshAtLevel(0,targetMesh)
meshMEDFile.setMeshAtLevel(-1,targetMesh1)
# Some groups on cells Level 0
- grp0_0 = ml.DataArrayInt([0,1,3])
+ grp0_0 = mc.DataArrayInt([0,1,3])
grp0_0.setName("grp0_Lev0")
- grp1_0 = ml.DataArrayInt([1,2,3,4])
+ grp1_0 = mc.DataArrayInt([1,2,3,4])
grp1_0.setName("grp1_Lev0")
meshMEDFile.setGroupsAtLevel(0, [grp0_0,grp1_0])
# Some groups on cells Level -1
- grp0_M1 = ml.DataArrayInt([0,1])
+ grp0_M1 = mc.DataArrayInt([0,1])
grp0_M1.setName("grp0_LevM1")
- grp1_M1 = ml.DataArrayInt([0,1,2])
+ grp1_M1 = mc.DataArrayInt([0,1,2])
grp1_M1.setName("grp1_LevM1")
- grp2_M1 = ml.DataArrayInt([1,2,3])
+ grp2_M1 = mc.DataArrayInt([1,2,3])
grp2_M1.setName("grp2_LevM1")
meshMEDFile.setGroupsAtLevel(-1,[grp0_M1,grp1_M1,grp2_M1])
# Write everything
meshMEDFile.write("TargetMesh2.med",2) # 2 stands for write from scratch
# Re-read and test equality
- meshMEDFileRead = ml.MEDFileMesh.New("TargetMesh2.med") # a new is needed because it returns a MEDFileUMesh (MEDFileMesh is abstract)
+ meshMEDFileRead = mc.MEDFileMesh.New("TargetMesh2.med") # a new is needed because it returns a MEDFileUMesh (MEDFileMesh is abstract)
meshRead0 = meshMEDFileRead.getMeshAtLevel(0)
meshRead1 = meshMEDFileRead.getMeshAtLevel(-1)
print("Is level 0 in the file equal to 'targetMesh'?", meshRead0.isEqual(targetMesh,1e-12))
#
# Fields
#
- f = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
f.setTime(5.6,7,8)
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
f.setName("AFieldName")
# Prepare field for writing
- fMEDFile = ml.MEDFileField1TS()
+ fMEDFile = mc.MEDFileField1TS()
fMEDFile.setFieldNoProfileSBT(f) # No profile desired on the field, Sort By Type
# *Append* the field to an existing file
fMEDFile.write("TargetMesh2.med",0) # 0 is very important here because we want to append to TargetMesh2.med and not to scratch it
# Read the field
- fMEDFileRead = ml.MEDFileField1TS("TargetMesh2.med",f.getName(),7,8)
- fRead1 = fMEDFileRead.getFieldOnMeshAtLevel(ml.ON_CELLS,0,meshMEDFileRead) # Quickest way, not re-reading mesh in the file.
- fRead2 = fMEDFileRead.getFieldAtLevel(ml.ON_CELLS,0) # Like above, but this time the mesh is read!
+ fMEDFileRead = mc.MEDFileField1TS("TargetMesh2.med",f.getName(),7,8)
+ fRead1 = fMEDFileRead.getFieldOnMeshAtLevel(mc.ON_CELLS,0,meshMEDFileRead) # Quickest way, not re-reading mesh in the file.
+ fRead2 = fMEDFileRead.getFieldAtLevel(mc.ON_CELLS,0) # Like above, but this time the mesh is read!
print("Does the field remain OK with the quick method?", fRead1.isEqual(f,1e-12,1e-12))
print("Does the field remain OK with the slow method?", fRead2.isEqual(f,1e-12,1e-12))
#
# Writing and Reading fields on profile using MEDLoader advanced API
#
- pfl = ml.DataArrayInt([1,2,3])
+ pfl = mc.DataArrayInt([1,2,3])
pfl.setName("My1stPfl")
fPart = f.buildSubPart(pfl)
fPart.setName("fPart")
#
- fMEDFile2 = ml.MEDFileField1TS()
+ fMEDFile2 = mc.MEDFileField1TS()
fMEDFile2.setFieldProfile(fPart,meshMEDFileRead,0,pfl) # 0 is the relative level (here 0 means 3D)
fMEDFile2.write("TargetMesh2.med",0) # 0 is paramount to indicate that we *append* (and no overwrite) to the MED file
#
- fMEDFileRead2 = ml.MEDFileField1TS("TargetMesh2.med",fPart.getName(),7,8)
- fPartRead, pflRead = fMEDFileRead2.getFieldWithProfile(ml.ON_CELLS,0,meshMEDFileRead)
+ fMEDFileRead2 = mc.MEDFileField1TS("TargetMesh2.med",fPart.getName(),7,8)
+ fPartRead, pflRead = fMEDFileRead2.getFieldWithProfile(mc.ON_CELLS,0,meshMEDFileRead)
print("Is the partial field correctly read?", fPartRead.isEqualWithoutConsideringStr(fPart.getArray(),1e-12))
print("Is the list of cell identifiers matching?", pflRead.isEqualWithoutConsideringStr(pfl))
::
- import MEDLoader as ml
+ import medcoupling as mc
# Mesh creation
targetCoords = [-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn = [0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh = ml.MEDCouplingUMesh("MyMesh",2)
+ targetMesh = mc.MEDCouplingUMesh("MyMesh",2)
targetMesh.allocateCells(5)
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[4:7])
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[7:10])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[0:4])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[10:14])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[14:18])
- myCoords = ml.DataArrayDouble(targetCoords,9,2)
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
+ myCoords = mc.DataArrayDouble(targetCoords,9,2)
myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
targetMesh.setCoords(myCoords)
# Writing mesh only
- ml.WriteUMesh("TargetMesh.med",targetMesh,True) # True means 'from scratch'
+ mc.WriteUMesh("TargetMesh.med",targetMesh,True) # True means 'from scratch'
# Re-read it and test equality
- meshRead = ml.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
+ meshRead = mc.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
print("Is the read mesh equal to 'targetMesh' ?", meshRead.isEqual(targetMesh,1e-12))
# Writing a field and its support mesh in one go
- f = ml.MEDCouplingFieldDouble.New(ml.ON_CELLS, ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble.New(mc.ON_CELLS, mc.ONE_TIME)
f.setTime(5.6,7,8) # Declare the timestep associated to the field
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
f.setName("AFieldName")
- ml.WriteField("MyFirstField.med",f,True)
+ mc.WriteField("MyFirstField.med",f,True)
# Re-read it and test equality
- f2 = ml.ReadFieldCell("MyFirstField.med", f.getMesh().getName(), 0, f.getName(), 7, 8)
+ f2 = mc.ReadFieldCell("MyFirstField.med", f.getMesh().getName(), 0, f.getName(), 7, 8)
print("Is the read field identical to 'f' ?", f2.isEqual(f,1e-12,1e-12))
# Writing in several steps
- ml.WriteUMesh("MySecondField.med",f.getMesh(),True)
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f)
+ mc.WriteUMesh("MySecondField.med",f.getMesh(),True)
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f)
# A second field to write
f2 = f.clone(True) # 'True' means that we need a deep copy
f2.getArray()[:] = 2.0
f2.setTime(7.8,9,10)
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
# Re-read and test this two-timestep field
- f3 = ml.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),7,8)
+ f3 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),7,8)
print("Is the field read in file equals to 'f' ?", f.isEqual(f3,1e-12,1e-12))
- f4 = ml.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),9,10)
+ f4 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),9,10)
print("Is the field read in file equals to 'f2' ?", f2.isEqual(f4,1e-12,1e-12))
::
- import MEDLoader as ml
+ import medcoupling as mc
- m0 = ml.MEDCouplingCMesh()
- arr = ml.DataArrayDouble(31,1) ; arr.iota(0.)
+ m0 = mc.MEDCouplingCMesh()
+ arr = mc.DataArrayDouble(31,1) ; arr.iota(0.)
m0.setCoords(arr,arr)
m0 = m0.buildUnstructured()
m00 = m0[::2] # Extract even cells
m00.simplexize(0)
m01 = m0[1::2]
- m0 = ml.MEDCouplingUMesh.MergeUMeshes([m00,m01])
+ m0 = mc.MEDCouplingUMesh.MergeUMeshes([m00,m01])
m0.getCoords()[:] *= 1/15.
m0.setName("mesh")
# Cell field
- cellField = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ cellField = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
cellField.setTime(5.6,5,6)
cellField.setMesh(m0)
cellField.setName("CellField")
cellField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))")
cellField.getArray().setInfoOnComponent(0,"powercell [W]")
# Node field
- nodeField = ml.MEDCouplingFieldDouble(ml.ON_NODES,ml.ONE_TIME)
+ nodeField = mc.MEDCouplingFieldDouble(mc.ON_NODES,mc.ONE_TIME)
nodeField.setTime(5.6,5,6)
nodeField.setMesh(m0)
nodeField.setName("NodeField")
nodeField1 = nodeField[proc1] ; cellField1 = cellField[proc1] ; cellField1.setMesh(nodeField1.getMesh())
proc0_fname = "proc0.med"
- ml.WriteField(proc0_fname, nodeField0, True)
- ml.WriteFieldUsingAlreadyWrittenMesh(proc0_fname, cellField0)
+ mc.WriteField(proc0_fname, nodeField0, True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc0_fname, cellField0)
proc1_fname = "proc1.med"
- ml.WriteField(proc1_fname,nodeField1,True)
- ml.WriteFieldUsingAlreadyWrittenMesh(proc1_fname,cellField1)
+ mc.WriteField(proc1_fname,nodeField1,True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc1_fname,cellField1)
#
# Merging - Sub-optimal method
#
- cellField0_read = ml.ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
- cellField1_read = ml.ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
- cellField_read = ml.MEDCouplingFieldDouble.MergeFields([cellField0_read,cellField1_read])
+ cellField0_read = mc.ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
+ cellField1_read = mc.ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
+ cellField_read = mc.MEDCouplingFieldDouble.MergeFields([cellField0_read,cellField1_read])
cellFieldCpy = cellField.deepCopy()
cellFieldCpy.substractInPlaceDM(cellField_read,10,1e-12)
cellFieldCpy.getArray().abs()
print(cellFieldCpy.getArray().isUniform(0.,1e-12))
#
- nodeField0_read = ml.ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
- nodeField1_read = ml.ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
- nodeField_read = ml.MEDCouplingFieldDouble.MergeFields([nodeField0_read, nodeField1_read])
+ nodeField0_read = mc.ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
+ nodeField1_read = mc.ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
+ nodeField_read = mc.MEDCouplingFieldDouble.MergeFields([nodeField0_read, nodeField1_read])
nodeField_read.mergeNodes(1e-10)
nodeFieldCpy = nodeField.deepCopy()
nodeFieldCpy.mergeNodes(1e-10)
# Merging - Optimal method
#
fileNames = ["proc0.med","proc1.med"]
- msML = [ml.MEDFileMesh.New(fname) for fname in fileNames]
- fsML = [ml.MEDFileFields.New(fname) for fname in fileNames]
- mergeMLMesh = ml.MEDFileUMesh()
- mergeMLFields = ml.MEDFileFields()
+ msML = [mc.MEDFileMesh.New(fname) for fname in fileNames]
+ fsML = [mc.MEDFileFields.New(fname) for fname in fileNames]
+ mergeMLMesh = mc.MEDFileUMesh()
+ mergeMLFields = mc.MEDFileFields()
for lev in msML[0].getNonEmptyLevels():
o2nML = len(msML[0].getNonEmptyLevels())*[None]
cs = [mML.getCoords() for mML in msML]
- mergeMLMesh.setCoords(ml.DataArrayDouble.Aggregate(cs))
+ mergeMLMesh.setCoords(mc.DataArrayDouble.Aggregate(cs))
ms = [mML.getMeshAtLevel(lev) for mML in msML]
- m = ml.MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
+ m = mc.MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
o2nML[lev] = m.sortCellsInMEDFileFrmt()
mergeMLMesh.setMeshAtLevel(lev,m)
pass
for fieldName in fsML[0].getFieldsNames():
fmts = [fML[fieldName] for fML in fsML]
- mergeField = ml.MEDFileFieldMultiTS()
+ mergeField = mc.MEDFileFieldMultiTS()
for dt,it,tim in fmts[0].getTimeSteps():
fts = [fmt[dt,it] for fmt in fmts]
arrs = len(fts)*[None]
for typp in fts[0].getTypesOfFieldAvailable():
arr1s = []
- if typp == ml.ON_CELLS:
+ if typp == mc.ON_CELLS:
for ft in fts:
for geoTyp,smth in ft.getFieldSplitedByType():
- if geoTyp != ml.NORM_ERROR:
- smth1 = filter(lambda x:x[0] == ml.ON_CELLS,smth)
+ if geoTyp != mc.NORM_ERROR:
+ smth1 = filter(lambda x:x[0] == mc.ON_CELLS,smth)
arr2s = [ft.getUndergroundDataArray()[elt[1][0]:elt[1][1]] for elt in smth1]
- arr1s.append(ml.DataArrayDouble.Aggregate(arr2s))
+ arr1s.append(mc.DataArrayDouble.Aggregate(arr2s))
pass
pass
pass
pass
else:
for ft in fts:
- smth = filter(lambda x:x[0] == ml.NORM_ERROR,ft.getFieldSplitedByType())
- arr2 = ml.DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
+ smth = filter(lambda x:x[0] == mc.NORM_ERROR,ft.getFieldSplitedByType())
+ arr2 = mc.DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
arr1s.append(arr2)
pass
pass
- arr = ml.DataArrayDouble.Aggregate(arr1s)
- if typp == ml.ON_CELLS:
+ arr = mc.DataArrayDouble.Aggregate(arr1s)
+ if typp == mc.ON_CELLS:
arr.renumberInPlace(o2nML[lev])
- mcf = ml.MEDCouplingFieldDouble(typp,ml.ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
+ mcf = mc.MEDCouplingFieldDouble(typp,mc.ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
mcf.setMesh(mergeMLMesh.getMeshAtLevel(lev)) ; mcf.checkConsistencyLight()
mergeField.appendFieldNoProfileSBT(mcf)
pass
Beginning of implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-To implement this exercice we use the python language script and import the MEDCoupling and MEDLoader parts of the MED module::
+To implement this exercice we use the python language script and import the medcoupling module. We need also mathematical functions, so we import the python math module::
- from MEDCoupling import *
- from MEDLoader import *
-
- from math import *
+ import medcoupling as mc
+ from math import *
Then we must instantiate a meshing object::
- mesh=MEDCouplingUMesh.New()
+ mesh=mc.MEDCouplingUMesh.New()
mesh.setMeshDimension(2)
mesh.allocateCells(numberOfCells)
mesh.setName("MaFleur")
for i in range(6):
...
- myCoords=DataArrayDouble.New()
+ myCoords=mc.DataArrayDouble.New()
myCoords.setValues(coordinates,numberOfNodes,2)
mesh.setCoords(myCoords)
connectivity.append(...)
connectivity.append(...)
for i in range(6):
- mesh.insertNextCell(NORM_TRI3,3,connectivity[3*i:3*(i+1)])
+ mesh.insertNextCell(mc.NORM_TRI3,3,connectivity[3*i:3*(i+1)])
pass
start = i%6+1
connectivity.append(...)
for i in range(6):
- mesh.insertNextCell(NORM_POLYGON,6,connectivity[6*i:6*(i+1)])
+ mesh.insertNextCell(mc.NORM_POLYGON,6,connectivity[6*i:6*(i+1)])
pass
mesh.checkConsistencyLight()
You have to create a med file with the MED driver::
medFileName = "MEDCoupling_Fleur.med"
- MEDLoader.WriteUMesh(medFileName,mesh,True)
+ mc.WriteUMesh(medFileName,mesh,True)
Visualize the mesh with SMESH module of Salome
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Beginning of implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-To implement this exercice we use the python language script and import the MEDCoupling and MEDLoader parts of the MED module. We need also mathematical functions, so we import the python math module::
+To implement this exercice we use the python language script and import the medcoupling module. We need also mathematical functions, so we import the python math module::
- from MEDCoupling import *
- from MEDLoader import *
+ import medcoupling as mc
from math import *
You must define 3 variables for space dimension, number of nodes on each dimension and total number of nodes::
::
- mesh=MEDCouplingUMesh.New()
+ mesh = mc.MEDCouplingUMesh.New()
mesh.setMeshDimension(3)
mesh.allocateCells(...)
mesh.setName("3Dcube")
for i in range(N):
coordinates.append(...)
- myCoords = DataArrayDouble.New()
+ myCoords = mc.DataArrayDouble.New()
myCoords.setValues(coordinates,nbOfNodes,3)
mesh.setCoords(myCoords)
# Adding cells in meshing
for i in range(nbOfCells):
- mesh.insertNextCell(NORM_HEXA8,8,connectivity[8*i:8*(i+1)])
+ mesh.insertNextCell(mc.NORM_HEXA8,8,connectivity[8*i:8*(i+1)])
pass
# Check mesh consistency:
coordinates.append(...)
...
Connectivities = [...]
- myCoords = DataArrayDouble.New()
+ myCoords = mc.DataArrayDouble.New()
myCoords.setValues(coordinates,NbNode2D,MeshDim2D)
- m1 = MEDCouplingUMesh.New()
+ m1 = mc.MEDCouplingUMesh.New()
m1.setMeshDimension(MeshDim2D)
m1.allocateCells(NbCell2D)
m1.setCoords(myCoords)
m1.setName("2D_Support")
for i in range(NbCell2D):
- m1.insertNextCell(NORM_QUAD4,4,Connectivities[4*i:4*(i+1)])
+ m1.insertNextCell(mc.NORM_QUAD4,4,Connectivities[4*i:4*(i+1)])
m1.changeSpaceDimension(3)
Definition of 1D mesh
coords = [ ... ]
conn = [ ... ]
- m2 = MEDCouplingUMesh.New()
+ m2 = mc.MEDCouplingUMesh.New()
m2.setMeshDimension(1)
m2.allocateCells(3)
- m2.insertNextCell(NORM_SEG2,2,conn[0:2])
- m2.insertNextCell(NORM_SEG2,2,conn[2:4])
- m2.insertNextCell(NORM_SEG2,2,conn[4:6])
- myCoords1D=DataArrayDouble.New()
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[0:2])
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[2:4])
+ m2.insertNextCell(mc.NORM_SEG2,2,conn[4:6])
+ myCoords1D=mc.DataArrayDouble.New()
myCoords1D.setValues(coords,4,1)
m2.setCoords(myCoords1D)
m2.changeSpaceDimension(3)
::
- mesh=MEDCouplingCMesh.New()
- coordsX=DataArrayDouble.New()
+ mesh=mc.MEDCouplingCMesh.New()
+ coordsX=mc.DataArrayDouble.New()
arrX=[ ... ]
coordsX.setValues(arrX,4,1)
- coordsY=DataArrayDouble.New()
+ coordsY=mc.DataArrayDouble.New()
arrY=[ ... ]
coordsY.setValues(arrY,4,1)
- coordsZ=DataArrayDouble.New()
+ coordsZ=mc.DataArrayDouble.New()
arrZ=[ ... ]
coordsZ.setValues(arrZ,4,1)
mesh.setCoords(coordsX,coordsY,coordsZ)
Generally ids cells using in group are known. So you just need put these ids in a DataArray.
::
- tabIdCells = DataArrayInt.New()
+ tabIdCells = mc.DataArrayInt.New()
IdCells = [ ... ]
tabIdCells.setValues(IdCells,...)
::
# Passing MEDCoupling to MEDFile
- fmeshU = MEDFileUMesh.New()
+ fmeshU = mc.MEDFileUMesh.New()
fmeshU.setName("Grid")
fmeshU.setDescription("IHopeToConvinceLastMEDMEMUsers")
myCoords = meshU.getCoords()
# => Definition of the mesh support
# => Definition of field name
# => Definition of field nature
- field = MEDCouplingFieldDouble.New(ON_CELLS)
+ field = mc.MEDCouplingFieldDouble.New(ON_CELLS)
field.setMesh(mesh)
field.setName("field")
field.setNature(ExtensiveMaximum)
# Computing and setting field values
- myCoords=DataArrayDouble.New()
+ myCoords=mc.DataArrayDouble.New()
sampleTab=[]
bar = mesh.computeCellCenterOfMass()
print(bar.getNbOfElems())
::
medFileName = "MEDCoupling_Extrudedcube3D.med"
- MEDLoader.WriteUMesh(medFileName,meshU,True)
+ mc.WriteUMesh(medFileName,meshU,True)
.. note:: True / False in Write* functions : True for overwriting existing file and False for adding in existing file
medFileName = "MEDCoupling_cube3D.med"
meshes=[mesh2D,mesh]
- MEDLoader.WriteUMeshes(medFileName,meshes,True)
+ mc.WriteUMeshes(medFileName,meshes,True)
Group Case
````````````
::
- MEDLoader.WriteField(medFileName,field,False)
+ mc.WriteField(medFileName,field,False)
Visualize the mesh with the SMESH module of Salome
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Beginning of implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
-To implement this exercice we use the python language script and import the MEDCoupling and MEDLoader parts of the MED module. We need also mathematical functions, so we import the python math module::
+To implement this exercice we use the python language script and import the medcoupling module. We need also mathematical functions, so we import the python math module::
- from MEDCoupling import *
- from MEDLoader import *
+ import medcoupling as mc
from math import *
and the iteration and order of the field. In our case, since there is no iteration, it's -1 for these 2 arguments::
- mesh3D = MEDLoader.ReadUMeshFromFile(medFileName,MeshName,0)
- f = MEDLoader.ReadFieldCell(medFileName,mesh3D.getName(),0,FieldName,-1,-1)
+ mesh3D = mc.ReadUMeshFromFile(medFileName,MeshName,0)
+ f = mc.ReadFieldCell(medFileName,mesh3D.getName(),0,FieldName,-1,-1)
Retrieving 2D mesh and associated field
Do the same thing for the 2D mesh and the associated field::
- mesh2D = MEDLoader.ReadUMeshFromFile(...)
- f2 = MEDLoader.ReadFieldCell(...)
+ mesh2D = mc.ReadUMeshFromFile(...)
+ f2 = mc.ReadFieldCell(...)
Retrieving mesh coords
~~~~~~~~~~~~~~~~~~~~~~
Implementation start
~~~~~~~~~~~~~~~~~~~~
-Import the whole Python module MEDLoader (which includes MEDCoupling).
-Also import NumPy and acos() from the math module. ::
+Import the whole Python module medcoupling.
+Also import NumPy. ::
- from MEDLoader import *
- from numpy import *
- from math import acos
+ import medcoupling as mc
+ import numpy as np
Mesh and field extraction using advanced API
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using the advanced API read the whole file "agitateur.med" and display all time-steps of
the first field. ::
- data=MEDFileData("agitateur.med")
+ data=mc.MEDFileData("agitateur.med")
ts=data.getFields()[0].getTimeSteps()
print(ts)
fMts=data.getFields()["DISTANCE_INTERFACE_ELEM_BODY_ELEM_DOM"]
f1ts=fMts[(2,-1)]
- fMc=f1ts.getFieldAtLevel(ON_CELLS,0)
+ fMc=f1ts.getFieldAtLevel(mc.ON_CELLS,0)
arr=fMc.getArray()
arr.getMinMaxPerComponent() # just to see the variation range of the field per component
ids=arr.findIdsInRange(0.,1.)
pressMts=data.getFields()["PRESSION_ELEM_DOM"]
press1ts=pressMts[(2,-1)]
- pressMc=press1ts.getFieldAtLevel(ON_CELLS,0)
+ pressMc=press1ts.getFieldAtLevel(mc.ON_CELLS,0)
pressOnAgitateurMc=pressMc[ids]
Delete unused nodes in pressOnAgitateurMc.getMesh(). ::
Compute the cross product for each cell of "posSkin" using "forceVectSkin"
(method DataArrayDouble.CrossProduct()). ::
- torquePerCellOnSkin=DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
+ torquePerCellOnSkin=mc.DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
Sum "torqueOnSkin" using DataArrayDouble.accumulate(). ::
speedMts=data.getFields()["VITESSE_ELEM_DOM"]
speed1ts=speedMts[(2,-1)]
- speedMc=speed1ts.getFieldAtLevel(ON_CELLS,0)
+ speedMc=speed1ts.getFieldAtLevel(mc.ON_CELLS,0)
speedOnSkin=speedMc.getArray()[tupleIdsInField]
- powerSkin=DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
+ powerSkin=mc.DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
power=powerSkin.accumulate()[0]
print("power = %r W"%(power))
Début de l'implémentation
~~~~~~~~~~~~~~~~~~~~~~~~~
-Pour commencer l'exercice importer tout le module python ``MEDLoader`` (qui inclut ``MEDCoupling``).
+Pour commencer l'exercice importer le module python ``medcoupling``.
Importer aussi ``numpy``. ::
- import MEDLoader as ml
+ import medcoupling as mc
import numpy as np
Extraction des maillages et champs avec l'API avancée
Avec l'API avancée lire tout le fichier "agitateur.med" et afficher tous les pas de temps du 1er champ. ::
- data = ml.MEDFileData("agitateur.med")
+ data = mc.MEDFileData("agitateur.med")
ts = data.getFields()[0].getTimeSteps()
print(ts)
fMts = data.getFields()["DISTANCE_INTERFACE_ELEM_BODY_ELEM_DOM"]
f1ts = fMts[(2,-1)]
- fMc = f1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ fMc = f1ts.getFieldAtLevel(mc.ON_CELLS,0)
arr = fMc.getArray()
arr.getMinMaxPerComponent() # just to see the field variation range per component
ids = arr.findIdsInRange(0.,1.)
pressMts = data.getFields()["PRESSION_ELEM_DOM"]
press1ts = pressMts[(2,-1)]
- pressMc = press1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ pressMc = press1ts.getFieldAtLevel(mc.ON_CELLS,0)
pressOnAgitateurMc = pressMc[ids]
Supprimer les noeuds inutiles de ``pressOnAgitateurMc.getMesh()`` : ::
Appliquer maintenant la formule classique de calcul du moment : calculer le produit
vectoriel par cellule de ``posSkin`` avec ``forceVectSkin`` (méthode ``DataArrayDouble.CrossProduct()``). ::
- torquePerCellOnSkin = ml.DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
+ torquePerCellOnSkin = mc.DataArrayDouble.CrossProduct(posSkin,forceVectSkin)
Sommer ``torqueOnSkin`` en utilisant la méthode ``DataArrayDouble.accumulate()``. ::
speedMts = data.getFields()["VITESSE_ELEM_DOM"]
speed1ts = speedMts[(2,-1)]
- speedMc = speed1ts.getFieldAtLevel(ml.ON_CELLS,0)
+ speedMc = speed1ts.getFieldAtLevel(mc.ON_CELLS,0)
speedOnSkin = speedMc.getArray()[tupleIdsInField]
- powerSkin = ml.DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
+ powerSkin = mc.DataArrayDouble.Dot(forceVectSkin,speedOnSkin)
power = powerSkin.accumulate()[0]
print("power = %r W"%(power))
Implementation start
~~~~~~~~~~~~~~~~~~~~
-Import the whole Python module MEDLoader (which includes MEDCoupling). ::
+To implement this exercise we use the Python scripting language and import the `medcoupling` Python module. ::
- from MEDLoader import *
+ import medcoupling as mc
Read and repare the static mesh "Fixe.med"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With the advanced API read the whole file "Fixe.med" and call "fixm" the MEDCouplingUMEsh instance
representing the static mesh. ::
- fixe=MEDFileMesh.New("Fixe.med")
- fixm=fixe.getMeshAtLevel(0)
+ fixe = mc.MEDFileMesh.New("Fixe.med")
+ fixm = fixe.getMeshAtLevel(0)
In what follows, it is required that any two cells touching each other share the same edges.
As we are in nodal connectivity mode it means that common nodes have to merged. This is not the case here.
Same thing for "Mobile.med" (called "mobm"). Repair it by deleting duplicated nodes. ::
- mobile=MEDFileMesh.New("Mobile.med")
+ mobile = mc.MEDFileMesh.New("Mobile.med")
mobm=mobile.getMeshAtLevel(0)
mobm.mergeNodes(1e-10)
The trick for now is to store QPOLYG in standard linear polygons and to convert them after reading.
Only "mobm" is concerned. Convert all polygonal cells in "mobm" into QPOLYG. ::
- ids=mobm.giveCellsWithType(NORM_POLYGON)
+ ids = mobm.giveCellsWithType(NORM_POLYGON)
mobm.getNodalConnectivity()[mobm.getNodalConnectivityIndex()[ids]]=NORM_QPOLYG
mobm.computeTypes()
It only take a cut fineness parameter (0.1 will suffice (angle expressed in rd)). Remember not to modify
neither "fixm" nor "mobm"! ::
- fixm2=fixm.deepCopy() # tessellate2D is non const - a mesh copy is required
+ fixm2 = fixm.deepCopy() # tessellate2D is non const - a mesh copy is required
fixm2.tessellate2D(0.1)
fixm2.writeVTK("fixm2.vtu")
- mobm2=mobm.deepCopy()
+ mobm2 = mobm.deepCopy()
mobm2.tessellate2D(0.1)
mobm2.writeVTK("mobm2.vtu")
Define a small method displayVTK() which we will use later on. ::
def displayVTK(m,fname):
- tmp=m.deepCopy()
+ tmp = m.deepCopy()
tmp.tessellate2D(0.1)
tmp.writeVTK(fname)
return
extract the first zone.
Name this new instance "zone1Mobm", remove all orphan nodes and display. ::
- zonesInMobm=mobm.partitionBySpreadZone()
+ zonesInMobm = mobm.partitionBySpreadZone()
print("number of zones in mobm : %i"%(len(zonesInMobm)))
- zone1Mobm=mobm[zonesInMobm[0]]
+ zone1Mobm = mobm[zonesInMobm[0]]
zone1Mobm.zipCoords()
displayVTK(zone1Mobm,"zone1Mobm.vtu")
To achieve this: reduce "fixm" taking only "fixm" cells located in the bounding box of "zone1Mobm" (MEDCouplingUMesh.getBoundingBox() and MEDCouplingUMesh.getCellsInBoundingBox()).
Name this object "partFixm", remove its orphan nodes and display it. ::
- ids2=fixm.getCellsInBoundingBox(zone1Mobm.getBoundingBox(),1e-10)
- partFixm=fixm[ids2]
+ ids2 = fixm.getCellsInBoundingBox(zone1Mobm.getBoundingBox(),1e-10)
+ partFixm = fixm[ids2]
partFixm.zipCoords()
displayVTK(partFixm,"partFixm.vtu")
In partFixMob merge common nodes with a threshold of 1e-10. ::
- partFixMob,iPart,iMob=MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
+ partFixMob,iPart,iMob = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
partFixMob.mergeNodes(1e-10)
Get and display partFixm part which is not in zone1Mobm. Call this mesh partFixmWithoutZone1Mobm. ::
- ids3=iMob.findIdsEqual(-1)
- partFixmWithoutZone1Mobm=partFixMob[ids3]
+ ids3 = iMob.findIdsEqual(-1)
+ partFixmWithoutZone1Mobm = partFixMob[ids3]
displayVTK(partFixmWithoutZone1Mobm,"partFixmWithoutZone1Mobm.vtu")
.. image:: images/partFixmWithoutZone1Mobm.jpg
all oriented consistently.
To check this let's inspect the areas of the 38 cells of partFixm (variable name "areaPartFixm"). ::
- areaPartFixm=partFixm.getMeasureField(isAbs=False).getArray()
+ areaPartFixm = partFixm.getMeasureField(isAbs=False).getArray()
print(areaPartFixm.getValues())
All values are negative: this MED file doesn't respect the MED file convention.
To cut long story short, we perform comparison on absolute arrays.
Check then that the first test check#0 is successful ::
- areaPartFixm=partFixm.getMeasureField(isAbs=False).getArray()
+ areaPartFixm = partFixm.getMeasureField(isAbs=False).getArray()
areaPartFixm.abs()
- areaPartFixMob=partFixMob.getMeasureField(isAbs=False).getArray()
+ areaPartFixMob = partFixMob.getMeasureField(isAbs=False).getArray()
areaPartFixMob.abs()
- val1=areaPartFixm.accumulate()[0]
- val2=areaPartFixMob.accumulate()[0]
+ val1 = areaPartFixm.accumulate()[0]
+ val2 = areaPartFixMob.accumulate()[0]
print("Check #0 %lf == %lf a 1e-8 ? %s"%(val1,val2,str(abs(val1-val2)<1e-8)))
Now check#1. Same spirit as in check#0. ::
- areaZone1Mobm=zone1Mobm.getMeasureField(isAbs=False).getArray()
+ areaZone1Mobm = zone1Mobm.getMeasureField(isAbs=False).getArray()
areaZone1Mobm.abs()
- val3=areaZone1Mobm.accumulate()[0]
- ids4=iMob.findIdsNotEqual(-1)
+ val3 = areaZone1Mobm.accumulate()[0]
+ ids4 = iMob.findIdsNotEqual(-1)
areaPartFixMob2=areaPartFixMob[ids4]
- val4=areaPartFixMob2.accumulate()[0]
+ val4 = areaPartFixMob2.accumulate()[0]
print("Check #1 %lf == %lf a 1e-8 ? %s"%(val3,val4,str(abs(val3-val4)<1e-8)))
Finally check#2. ::
- isCheck2OK=True
+ isCheck2OK = True
for icell in list(range(partFixm.getNumberOfCells())):
- ids5=iPart.findIdsEqual(icell)
- areaOfCells=areaPartFixMob[ids5]
+ ids5 = iPart.findIdsEqual(icell)
+ areaOfCells = areaPartFixMob[ids5]
areaOfCells.abs()
if abs(areaOfCells.accumulate()[0]-areaPartFixm[icell])>1e-9:
- isCheck2OK=False
+ isCheck2OK = False
pass
pass
print("Check #2? %s"%(str(isCheck2OK)))
Now create a cell field on partFixMob by setting it to 0 on the part covering only partFixm and 1 on the overlapped
part. Visualize it in a VTK file. ::
- f=MEDCouplingFieldDouble(ON_CELLS,ONE_TIME)
- m=partFixMob.deepCopy() ; m.tessellate2D(0.1)
+ f = mc.MEDCouplingFieldDouble(ON_CELLS,ONE_TIME)
+ m = partFixMob.deepCopy() ; m.tessellate2D(0.1)
f.setMesh(m)
- arr=DataArrayDouble(partFixMob.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob.getNumberOfCells(),1)
arr[iMob.findIdsEqual(-1)]=0.
arr[iMob.findIdsNotEqual(-1)]=1.
f.setArray(arr)
f.checkConsistencyLight()
f.setName("Zone")
- MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
.. image:: images/LocationEx2.jpg
Create a cell field whose value is 0 in the zone being exclusively part of fixm,
1 in the zone #0, 2 in the zone #1 and 3 in the zone #5. ::
- zonesMobm=MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
+ zonesMobm = mc.MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
zonesMobm.zipCoords()
- partFixMob2,iPart2,iMob2=MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
+ partFixMob2,iPart2,iMob2 = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
partFixMob2.mergeNodes(1e-10)
- f2=MEDCouplingFieldDouble(ON_CELLS,ONE_TIME)
- m2=partFixMob2.deepCopy() ; m2.tessellate2D(0.1)
+ f2 = mc.MEDCouplingFieldDouble(ON_CELLS,ONE_TIME)
+ m2 = partFixMob2.deepCopy() ; m2.tessellate2D(0.1)
f2.setMesh(m2)
- arr=DataArrayDouble(partFixMob2.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob2.getNumberOfCells(),1)
arr[iMob2.findIdsEqual(-1)]=0.
- st=0 ; end=st+len(zonesInMobm[0])
+ st=0 ; end = st+len(zonesInMobm[0])
arr[iMob2.findIdsInRange(st,end)]=1.
- st+=len(zonesInMobm[0]) ; end=st+len(zonesInMobm[1])
+ st += len(zonesInMobm[0]) ; end=st+len(zonesInMobm[1])
arr[iMob2.findIdsInRange(st,end)]=2.
- st+=len(zonesInMobm[1]) ; end=st+len(zonesInMobm[2])
+ st += len(zonesInMobm[1]) ; end=st+len(zonesInMobm[2])
arr[iMob2.findIdsInRange(st,end)]=3.
f2.setArray(arr)
f2.checkConsistencyLight()
f2.setName("Zone2")
- MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
.. image:: images/zonesMobm.jpg
Début de l'implémentation
~~~~~~~~~~~~~~~~~~~~~~~~~
-Pour commencer l'exercice importer tout le module python MEDLoader (qui inclus MEDCoupling). ::
+Cet exercice repose comme tous les autres sur le language de script Python. On charge
+le module Python ``medcoupling``.::
- import MEDLoader as ml
+ import medcoupling as mc
Lire et réparer le maillage statique "Fixe.med"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Avec l'API avancée lire tout le fichier "Fixe.med" et appeler ``fixm``
l'objet de type ``MEDCouplingUMesh`` représentant le maillage statique. ::
- fixe = ml.MEDFileMesh.New("Fixe.med")
+ fixe = mc.MEDFileMesh.New("Fixe.med")
fixm = fixe.getMeshAtLevel(0)
Pour ce qui suit il faut absolument que deux cellules se touchant partagent les mêmes edges. Pour ce faire, comme on est
Même traitement pour ``Mobile.med``, le lire avec l'API avancée de MEDLoader (appeler ``mobm`` l'instance du maillage)
et le réparer en supprimant les noeuds dupliqués. ::
- mobile = ml.MEDFileMesh.New("Mobile.med")
+ mobile = mc.MEDFileMesh.New("Mobile.med")
mobm = mobile.getMeshAtLevel(0)
mobm.mergeNodes(1e-10)
Sur ``partFixMob`` merger les noeuds à 1e-10 près. ::
- partFixMob, iPart, iMob = ml.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
+ partFixMob, iPart, iMob = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zone1Mobm,1e-10)
partFixMob.mergeNodes(1e-10)
Récupérer et afficher la partie de ``partFixm`` qui n'est pas dans ``zone1Mobm``. Appeler ce maillage ``partFixmWithoutZone1Mobm``. ::
exclusive ``partFixm`` et 1 sur la partie couverte. Nous créons donc un champ représentant une fonction indicatrice.
Le visualiser en utilisant un fichier VTK (ne pas oublier l'option *Triangulate* de ParaView). ::
- f = ml.MEDCouplingFieldDouble(ml.ON_CELLS,ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble(mc.ON_CELLS,mc.ONE_TIME)
m = partFixMob.deepCopy()
m.tessellate2D(0.1)
f.setMesh(m)
- arr = ml.DataArrayDouble(partFixMob.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob.getNumberOfCells(),1)
arr[iMob.findIdsEqual(-1)] = 0.
arr[iMob.findIdsNotEqual(-1)] = 1.
f.setArray(arr)
f.checkConsistencyLight()
f.setName("Zone")
- ml.MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone.vtu",[f])
.. image:: images/LocationEx2.jpg
:scale: 100
Plus généralement prendre les zones 0, 1 et 5. Faire un champ aux cellules qui vaut 0 dans la zone exclusivement de ``fixm``,
1 dans zone #0, 2 dans la zone #1 et finalement 3 dans la zone #5. ::
- zonesMobm = ml.MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
+ zonesMobm = mc.MEDCouplingUMesh.MergeUMeshesOnSameCoords([mobm[zonesInMobm[0]], mobm[zonesInMobm[1]], mobm[zonesInMobm[5]]])
zonesMobm.zipCoords()
- partFixMob2,iPart2,iMob2 = ml.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
+ partFixMob2,iPart2,iMob2 = mc.MEDCouplingUMesh.Intersect2DMeshes(partFixm,zonesMobm,1e-10)
partFixMob2.mergeNodes(1e-10)
- f2 = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ f2 = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
m2 = partFixMob2.deepCopy()
m2.tessellate2D(0.1)
f2.setMesh(m2)
- arr = ml.DataArrayDouble(partFixMob2.getNumberOfCells(),1)
+ arr = mc.DataArrayDouble(partFixMob2.getNumberOfCells(),1)
arr[iMob2.findIdsEqual(-1)]=0.
st = 0
end = st + len(zonesInMobm[0])
f2.setArray(arr)
f2.checkConsistencyLight()
f2.setName("Zone2")
- ml.MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
+ mc.MEDCouplingFieldDouble.WriteVTK("Zone2.vtu",[f2])
Ne pas oublier l'option *Triangulate* de ParaView dans le panneau Display pour bien voir les champs:
Create an unstructured mesh "m0" built from a 30x30 structured mesh (meshDim=2, spaceDim=2).
Each of the even cell of "m0" is "simplexized" (cut in triangles - method MEDCouplingUMesh.simplexize(0)) ::
- from MEDLoader import *
- m0=MEDCouplingCMesh()
- arr=DataArrayDouble(31,1) ; arr.iota(0.)
- m0.setCoords(arr,arr)
- m0=m0.buildUnstructured()
- m00=m0[::2] # Extract even cells
- m00.simplexize(0)
- m01=m0[1::2]
- m0=MEDCouplingUMesh.MergeUMeshes([m00,m01])
- m0.getCoords()[:]*=1/15. # Illustrate how to quickly rescale a mesh
- m0.setName("mesh")
+ import medcoupling as mc
+
+ m0 = mc.MEDCouplingCMesh()
+ arr = mc.DataArrayDouble(31,1) ; arr.iota(0.)
+ m0.setCoords(arr,arr)
+ m0 = m0.buildUnstructured()
+ m00 = m0[::2] # Extract even cells
+ m00.simplexize(0)
+ m01 = m0[1::2]
+ m0 = mc.MEDCouplingUMesh.MergeUMeshes([m00,m01])
+ m0.getCoords()[:] *= 1/15. # Illustrate how to quickly rescale a mesh
+ m0.setName("mesh")
.. note:: The call to setName() on "m0" is mandatory. Don't forget that the correct naming of the meshes is paramount in the MED file context.
Create the fields "CellField" and "NodeField" at the time-stamp (5,6) corresponding to 5.6s.
::
- CellField=MEDCouplingFieldDouble(ON_CELLS,ONE_TIME) ; CellField.setTime(5.6,5,6) ; CellField.setMesh(m0)
- CellField.setName("CellField")
- CellField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))") ; CellField.getArray().setInfoOnComponent(0,"powercell [W]")
- NodeField=MEDCouplingFieldDouble(ON_NODES,ONE_TIME) ; NodeField.setTime(5.6,5,6) ; NodeField.setMesh(m0)
- NodeField.setName("NodeField")
- NodeField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))") ; NodeField.getArray().setInfoOnComponent(0,"powernode [W]")
+ # Cell field
+ cellField = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
+ cellField.setTime(5.6,5,6)
+ cellField.setMesh(m0)
+ cellField.setName("CellField")
+ cellField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))")
+ cellField.getArray().setInfoOnComponent(0,"powercell [W]")
+ # Node field
+ nodeField = mc.MEDCouplingFieldDouble(mc.ON_NODES,mc.ONE_TIME)
+ nodeField.setTime(5.6,5,6)
+ nodeField.setMesh(m0)
+ nodeField.setName("NodeField")
+ nodeField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))")
+ nodeField.getArray().setInfoOnComponent(0,"powernode [W]")
"CellField" looks like this:
Mesh partitionning
~~~~~~~~~~~~~~~~~~
-Cut "m0" into two distinct parts called "proc0" and "proc1". "proc0" will be contained in the bounding box [(0.,0.4),(0.,0.4)] (with a precision of 1e-10). Use the method MEDCouplingUMesh.getCellsInBoundingBox(). "proc1" is simply the complementary part of "proc0" (method DataArrayInt.buildComplement()). ::
+Cut "m0" into two distinct parts called "proc0" and "proc1". "proc0" will be contained in the bounding box [(0.,0.4),(0.,0.4)] (with a precision of 1e-10). Use the method MEDCouplingUMesh.getCellsInBoundingBox(). "proc1" is simply the complementary part of "proc0" (method DataArrayInt.buildComplement()).
+::
- proc0=m0.getCellsInBoundingBox([(0.,0.4),(0.,0.4)],1e-10)
- proc1=proc0.buildComplement(m0.getNumberOfCells())
+ proc0 = m0.getCellsInBoundingBox([(0.,0.4),(0.,0.4)],1e-10)
+ proc1 = proc0.buildComplement(m0.getNumberOfCells())
.. image:: images/SplitAndMerge2.jpg
Starting with the partition above ("proc0" and "proc1") create two MED files called "proc0.med" et "proc1.med". ::
- NodeField0=NodeField[proc0] ; CellField0=CellField[proc0] ; CellField0.setMesh(NodeField0.getMesh())
- NodeField1=NodeField[proc1] ; CellField1=CellField[proc1] ; CellField1.setMesh(NodeField1.getMesh())
-
- proc0_fname="proc0.med"
- WriteField(proc0_fname,NodeField0,True)
- WriteFieldUsingAlreadyWrittenMesh(proc0_fname,CellField0)
-
- proc1_fname="proc1.med"
- WriteField(proc1_fname,NodeField1,True)
- WriteFieldUsingAlreadyWrittenMesh(proc1_fname,CellField1)
+ nodeField0 = nodeField[proc0] ; cellField0 = cellField[proc0] ; cellField0.setMesh(nodeField0.getMesh())
+ nodeField1 = nodeField[proc1] ; cellField1 = cellField[proc1] ; cellField1.setMesh(nodeField1.getMesh())
+
+ proc0_fname = "proc0.med"
+ mc.WriteField(proc0_fname, nodeField0, True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc0_fname, cellField0)
+
+ proc1_fname = "proc1.med"
+ mc.WriteField(proc1_fname,nodeField1,True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc1_fname,cellField1)
Reading and merging 2 MED files - Easy (but non optimal) version
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the two files "proc0.med" and "proc1.med" read the respective "CellField" with the basic API. Aggregate the two and store the result in "CellField_read". ::
- CellField0_read=ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
- CellField1_read=ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
- CellField_read=MEDCouplingFieldDouble.MergeFields([CellField0_read,CellField1_read])
+ cellField0_read = mc.ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
+ cellField1_read = mc.ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
+ cellField_read = mc.MEDCouplingFieldDouble.MergeFields([cellField0_read,cellField1_read])
.. note:: It might seem to the reader that the cell type information is repeated uselessly, but don't forget that the MED file norm doesn't forbid a field to be defined simultaneously on nodes and on Gauss points for example ...
Compare "CellField_read" and "CellField0". Problem: because of the constraint on the MED file numbering, the initial numbering has been lost. Or more exactly there is no standard way to retrieve it. This means that a call to MEDCouplingFieldDouble.isEqual() won't succeed. Let's use the method MEDCouplingFieldDouble.substractInPlaceDM() which operates a renumbering based on a given policy (see HTML doc).
To this end, create a deep copy of "CellField" into "CellFieldCpy" and invoke substractInPlaceDM() on it (DM stands for "Different Meshes", contrarily to substract() which only succeeds if the fields share the same mesh). ::
- CellFieldCpy=CellField.deepCopy()
- CellFieldCpy.substractInPlaceDM(CellField_read,10,1e-12)
- CellFieldCpy.getArray().abs()
- print(CellFieldCpy.getArray().isUniform(0.,1e-12))
+ cellFieldCpy = cellField.deepCopy()
+ cellFieldCpy.substractInPlaceDM(cellField_read,10,1e-12)
+ cellFieldCpy.getArray().abs()
+ print(cellFieldCpy.getArray().isUniform(0.,1e-12))
Let's do the same on "NodeField". The main difference here is that redundant information is created at the boundary. ::
- NodeField0_read=ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
- NodeField1_read=ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
- NodeField_read=MEDCouplingFieldDouble.MergeFields([NodeField0_read,NodeField1_read])
+ nodeField0_read = mc.ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
+ nodeField1_read = mc.ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
+ nodeField_read = mc.MEDCouplingFieldDouble.MergeFields([nodeField0_read, nodeField1_read])
.. note:: The mesh is read a second time here, which can be damaging in terms of performance.
Invoke MEDCouplingUMesh.mergeNodes() on "NodeField_read" to remove duplicate nodes.
Make a deep copy called "NodeFieldCpy" from "NodeField" and call MEDCouplingUMesh.mergeNodes(). ::
- NodeField_read.mergeNodes(1e-10)
- NodeFieldCpy=NodeField.deepCopy()
- NodeFieldCpy.mergeNodes(1e-10)
+ nodeField_read.mergeNodes(1e-10)
+ nodeFieldCpy = nodeField.deepCopy()
+ nodeFieldCpy.mergeNodes(1e-10)
.. note:: mergeNodes() takes two epsilons: the first classical one on the absolute distance between nodes, and the second expressing a tolerance on the values. If the field value of two nodes to be merged is bigger than this an exception is raised.
Compare "NodeFieldCpy" and "NodeField_read" still using MEDCouplingFieldDouble.substractInPlaceDM(). ::
- NodeFieldCpy.substractInPlaceDM(NodeField_read,10,1e-12)
- print(NodeFieldCpy.getArray().isUniform(0.,1e-12))
+ nodeFieldCpy.substractInPlaceDM(nodeField_read,10,1e-12)
+ print(nodeFieldCpy.getArray().isUniform(0.,1e-12))
Read/write of two separated MED files - More complex but more efficient version
Handle all the levels (even if there is only one in the present case) using the method
MEDFileUMesh.getNonEmptyLevels() on the instance coming from "proc0.med". ::
- fileNames=["proc0.med","proc1.med"]
- msML=[MEDFileMesh.New(fname) for fname in fileNames]
- fsML=[MEDFileFields.New(fname) for fname in fileNames]
- mergeMLMesh=MEDFileUMesh()
- mergeMLFields=MEDFileFields()
- for lev in msML[0].getNonEmptyLevels():
- o2nML=len(msML[0].getNonEmptyLevels())*[None]
- cs=[mML.getCoords() for mML in msML]
- mergeMLMesh.setCoords(DataArrayDouble.Aggregate(cs))
- ms=[mML.getMeshAtLevel(lev) for mML in msML]
- m=MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
- o2nML[lev]=m.sortCellsInMEDFileFrmt()
- mergeMLMesh.setMeshAtLevel(lev,m)
- pass
-
- for fieldName in fsML[0].getFieldsNames():
- fmts=[fML[fieldName] for fML in fsML]
- mergeField=MEDFileFieldMultiTS()
- for dt,it,tim in fmts[0].getTimeSteps():
- fts=[fmt[dt,it] for fmt in fmts]
- arrs=len(fts)*[None]
- for typp in fts[0].getTypesOfFieldAvailable():
- arr1s=[]
- if typp==ON_CELLS:
- for ft in fts:
- for geoTyp,smth in ft.getFieldSplitedByType():
- if geoTyp!=NORM_ERROR:
- smth1=filter(lambda x:x[0]==ON_CELLS,smth)
- arr2s=[ft.getUndergroundDataArray()[elt[1][0]:elt[1][1]] for elt in smth1]
- arr1s.append(DataArrayDouble.Aggregate(arr2s))
- pass
- pass
- pass
- pass
- else:
- for ft in fts:
- smth=filter(lambda x:x[0]==NORM_ERROR,ft.getFieldSplitedByType())
- arr2=DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
- arr1s.append(arr2)
- pass
- pass
- arr=DataArrayDouble.Aggregate(arr1s)
- if typp==ON_CELLS:
+ fileNames = ["proc0.med","proc1.med"]
+ msML = [mc.MEDFileMesh.New(fname) for fname in fileNames]
+ fsML = [mc.MEDFileFields.New(fname) for fname in fileNames]
+ mergeMLMesh = mc.MEDFileUMesh()
+ mergeMLFields = mc.MEDFileFields()
+ for lev in msML[0].getNonEmptyLevels():
+ o2nML = len(msML[0].getNonEmptyLevels())*[None]
+ cs = [mML.getCoords() for mML in msML]
+ mergeMLMesh.setCoords(mc.DataArrayDouble.Aggregate(cs))
+ ms = [mML.getMeshAtLevel(lev) for mML in msML]
+ m = mc.MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
+ o2nML[lev] = m.sortCellsInMEDFileFrmt()
+ mergeMLMesh.setMeshAtLevel(lev,m)
+ pass
+
+ for fieldName in fsML[0].getFieldsNames():
+ fmts = [fML[fieldName] for fML in fsML]
+ mergeField = mc.MEDFileFieldMultiTS()
+ for dt,it,tim in fmts[0].getTimeSteps():
+ fts = [fmt[dt,it] for fmt in fmts]
+ arrs = len(fts)*[None]
+ for typp in fts[0].getTypesOfFieldAvailable():
+ arr1s = []
+ if typp == mc.ON_CELLS:
+ for ft in fts:
+ for geoTyp,smth in ft.getFieldSplitedByType():
+ if geoTyp != mc.NORM_ERROR:
+ smth1 = filter(lambda x:x[0] == mc.ON_CELLS,smth)
+ arr2s = [ft.getUndergroundDataArray()[elt[1][0]:elt[1][1]] for elt in smth1]
+ arr1s.append(mc.DataArrayDouble.Aggregate(arr2s))
+ pass
+ pass
+ pass
+ pass
+ else:
+ for ft in fts:
+ smth = filter(lambda x:x[0] == mc.NORM_ERROR,ft.getFieldSplitedByType())
+ arr2 = mc.DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
+ arr1s.append(arr2)
+ pass
+ pass
+ arr = mc.DataArrayDouble.Aggregate(arr1s)
+ if typp == mc.ON_CELLS:
arr.renumberInPlace(o2nML[lev])
- mcf=MEDCouplingFieldDouble(typp,ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
- mcf.setMesh(mergeMLMesh.getMeshAtLevel(lev)) ; mcf.checkConsistencyLight()
- mergeField.appendFieldNoProfileSBT(mcf)
- pass
- pass
- mergeMLFields.pushField(mergeField)
- pass
- mergeMLMesh.write("merge.med",2)
- mergeMLFields.write("merge.med",0)
+ mcf = mc.MEDCouplingFieldDouble(typp,mc.ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
+ mcf.setMesh(mergeMLMesh.getMeshAtLevel(lev)) ; mcf.checkConsistencyLight()
+ mergeField.appendFieldNoProfileSBT(mcf)
+ pass
+ pass
+ mergeMLFields.pushField(mergeField)
+ pass
+ mergeMLMesh.write("merge.med",2)
+ mergeMLFields.write("merge.med",0)
Solution
Créer un unstructured mesh ``m0`` issu d'un maillage structuré (meshDim=2, spaceDim=2) de 30*30.
Chacune des cellules paires du maillage sera *simplexisée* (i.e. coupée en triangle - méthode ``MEDCouplingUMesh.simplexize(0)``) ::
- import MEDLoader as ml
+ import medcoupling as mc
- m0 = ml.MEDCouplingCMesh()
- arr = ml.DataArrayDouble(31,1) ; arr.iota(0.)
+ m0 = mc.MEDCouplingCMesh()
+ arr = mc.DataArrayDouble(31,1) ; arr.iota(0.)
m0.setCoords(arr,arr)
m0 = m0.buildUnstructured()
m00 = m0[::2] # Extract even cells
m00.simplexize(0)
m01 = m0[1::2]
- m0 = ml.MEDCouplingUMesh.MergeUMeshes([m00,m01])
+ m0 = mc.MEDCouplingUMesh.MergeUMeshes([m00,m01])
m0.getCoords()[:] *= 1/15. # Illustrate how to quickly rescale a mesh
m0.setName("mesh")
Créer les champs ``cellField`` et ``nodeField`` au pas de temps identifié à (5,6) et au pas de temps 5.6 s. ::
# Cell field
- cellField = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ cellField = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
cellField.setTime(5.6,5,6)
cellField.setMesh(m0)
cellField.setName("CellField")
cellField.fillFromAnalytic(1,"exp(-((x-1)*(x-1)+(y-1)*(y-1)))")
cellField.getArray().setInfoOnComponent(0,"powercell [W]")
# Node field
- nodeField = ml.MEDCouplingFieldDouble(ml.ON_NODES,ml.ONE_TIME)
+ nodeField = mc.MEDCouplingFieldDouble(mc.ON_NODES,mc.ONE_TIME)
nodeField.setTime(5.6,5,6)
nodeField.setMesh(m0)
nodeField.setName("NodeField")
nodeField1 = nodeField[proc1] ; cellField1 = cellField[proc1] ; cellField1.setMesh(nodeField1.getMesh())
proc0_fname = "proc0.med"
- ml.WriteField(proc0_fname, nodeField0, True)
- ml.WriteFieldUsingAlreadyWrittenMesh(proc0_fname, cellField0)
+ mc.WriteField(proc0_fname, nodeField0, True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc0_fname, cellField0)
proc1_fname = "proc1.med"
- ml.WriteField(proc1_fname,nodeField1,True)
- ml.WriteFieldUsingAlreadyWrittenMesh(proc1_fname,cellField1)
+ mc.WriteField(proc1_fname,nodeField1,True)
+ mc.WriteFieldUsingAlreadyWrittenMesh(proc1_fname,cellField1)
Lecture et fusion des 2 fichiers MED séparés (non optimal)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Partant de "proc0.med" et de "proc1.med" lire leur "CellField" respectif avec l'API basique,
agréger les deux et mettre le résultat dans ``cellField_read`` : ::
- cellField0_read = ml.ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
- cellField1_read = ml.ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
- cellField_read = ml.MEDCouplingFieldDouble.MergeFields([cellField0_read,cellField1_read])
+ cellField0_read = mc.ReadFieldCell("proc0.med","mesh",0,"CellField",5,6)
+ cellField1_read = mc.ReadFieldCell("proc1.med","mesh",0,"CellField",5,6)
+ cellField_read = mc.MEDCouplingFieldDouble.MergeFields([cellField0_read,cellField1_read])
.. note:: On peut avoir l'impression que l'information Cell (méthode ``ReadFieldCell``) est répétée de manière abusive
(effectivement le champ "CellField" a été créé aux cellules),
La différence ici c'est qu'il va y avoir duplication de l'information à la frontière, car les noeuds limites sont partagés
des deux côtés : ::
- nodeField0_read = ml.ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
- nodeField1_read = ml.ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
- nodeField_read = ml.MEDCouplingFieldDouble.MergeFields([nodeField0_read, nodeField1_read])
+ nodeField0_read = mc.ReadFieldNode("proc0.med","mesh",0,"NodeField",5,6)
+ nodeField1_read = mc.ReadFieldNode("proc1.med","mesh",0,"NodeField",5,6)
+ nodeField_read = mc.MEDCouplingFieldDouble.MergeFields([nodeField0_read, nodeField1_read])
.. note:: Dans cette partie, on a donc relu le maillage une deuxième fois ce qui peut être pénalisant ...
différents types géométriques : ::
fileNames = ["proc0.med","proc1.med"]
- msML = [ml.MEDFileMesh.New(fname) for fname in fileNames]
- fsML = [ml.MEDFileFields.New(fname) for fname in fileNames]
- mergeMLMesh = ml.MEDFileUMesh()
- mergeMLFields = ml.MEDFileFields()
+ msML = [mc.MEDFileMesh.New(fname) for fname in fileNames]
+ fsML = [mc.MEDFileFields.New(fname) for fname in fileNames]
+ mergeMLMesh = mc.MEDFileUMesh()
+ mergeMLFields = mc.MEDFileFields()
for lev in msML[0].getNonEmptyLevels():
o2nML = len(msML[0].getNonEmptyLevels())*[None]
cs = [mML.getCoords() for mML in msML]
- mergeMLMesh.setCoords(ml.DataArrayDouble.Aggregate(cs))
+ mergeMLMesh.setCoords(mc.DataArrayDouble.Aggregate(cs))
ms = [mML.getMeshAtLevel(lev) for mML in msML]
- m = ml.MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
+ m = mc.MEDCouplingUMesh.MergeUMeshes(ms) ; m.setCoords(mergeMLMesh.getCoords())
o2nML[lev] = m.sortCellsInMEDFileFrmt()
mergeMLMesh.setMeshAtLevel(lev,m)
pass
for fieldName in fsML[0].getFieldsNames():
fmts = [fML[fieldName] for fML in fsML]
- mergeField = ml.MEDFileFieldMultiTS()
+ mergeField = mc.MEDFileFieldMultiTS()
for dt,it,tim in fmts[0].getTimeSteps():
fts = [fmt[dt,it] for fmt in fmts]
arrs = len(fts)*[None]
for typp in fts[0].getTypesOfFieldAvailable():
arr1s = []
- if typp == ml.ON_CELLS:
+ if typp == mc.ON_CELLS:
for ft in fts:
for geoTyp,smth in ft.getFieldSplitedByType():
- if geoTyp != ml.NORM_ERROR:
- smth1 = filter(lambda x:x[0] == ml.ON_CELLS,smth)
+ if geoTyp != mc.NORM_ERROR:
+ smth1 = filter(lambda x:x[0] == mc.ON_CELLS,smth)
arr2s = [ft.getUndergroundDataArray()[elt[1][0]:elt[1][1]] for elt in smth1]
- arr1s.append(ml.DataArrayDouble.Aggregate(arr2s))
+ arr1s.append(mc.DataArrayDouble.Aggregate(arr2s))
pass
pass
pass
pass
else:
for ft in fts:
- smth = filter(lambda x:x[0] == ml.NORM_ERROR,ft.getFieldSplitedByType())
- arr2 = ml.DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
+ smth = filter(lambda x:x[0] == mc.NORM_ERROR,ft.getFieldSplitedByType())
+ arr2 = mc.DataArrayDouble.Aggregate([ft.getUndergroundDataArray()[elt[1][0][1][0]:elt[1][0][1][1]] for elt in smth])
arr1s.append(arr2)
pass
pass
- arr = ml.DataArrayDouble.Aggregate(arr1s)
- if typp == ml.ON_CELLS:
+ arr = mc.DataArrayDouble.Aggregate(arr1s)
+ if typp == mc.ON_CELLS:
arr.renumberInPlace(o2nML[lev])
- mcf = ml.MEDCouplingFieldDouble(typp,ml.ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
+ mcf = mc.MEDCouplingFieldDouble(typp,mc.ONE_TIME) ; mcf.setName(fieldName) ; mcf.setTime(tim,dt,it) ; mcf.setArray(arr)
mcf.setMesh(mergeMLMesh.getMeshAtLevel(lev)) ; mcf.checkConsistencyLight()
mergeField.appendFieldNoProfileSBT(mcf)
pass
Implementation start
~~~~~~~~~~~~~~~~~~~~
-To implement this exercise we use the Python scripting language and import the MEDLoader Python module.
-The whole MEDCoupling module is fully included in MEDLoader. No need to import medcoupling when MEDLoader has been loaded. ::
+To implement this exercise we use the Python scripting language and import the `medcoupling` Python module. ::
+
+ import medcoupling as mc
- import MEDLoader as ml
Writing and Reading meshes using MEDLoader's advanced API
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
targetCoords=[-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn=[0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh=ml.MEDCouplingUMesh.New("MyMesh",2)
+ targetMesh=mc.MEDCouplingUMesh.New("MyMesh",2)
targetMesh.allocateCells(5)
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[4:7])
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[7:10])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[0:4])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[10:14])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[14:18])
- myCoords=ml.DataArrayDouble.New(targetCoords,9,2)
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
+ myCoords=mc.DataArrayDouble.New(targetCoords,9,2)
targetMesh.setCoords(myCoords)
Then we are ready to write targetMesh and targetMesh1 into TargetMesh2.med. ::
- meshMEDFile=ml.MEDFileUMesh.New()
+ meshMEDFile=mc.MEDFileUMesh.New()
meshMEDFile.setMeshAtLevel(0,targetMesh)
meshMEDFile.setMeshAtLevel(-1,targetMesh1)
meshMEDFile.write("TargetMesh2.med",2) # 2 stands for write from scratch
Create 2 groups on level 0. The first called "grp0_Lev0" on cells [0,1,3] and the second called "grp1_Lev0" on cells [1,2,3,4] ::
- grp0_0=ml.DataArrayInt.New([0,1,3]) ; grp0_0.setName("grp0_Lev0")
- grp1_0=ml.DataArrayInt.New([1,2,3,4]) ; grp1_0.setName("grp1_Lev0")
+ grp0_0=mc.DataArrayInt.New([0,1,3]) ; grp0_0.setName("grp0_Lev0")
+ grp1_0=mc.DataArrayInt.New([1,2,3,4]) ; grp1_0.setName("grp1_Lev0")
meshMEDFile.setGroupsAtLevel(0,[grp0_0,grp1_0])
Create 3 groups on level -1. The 1st called "grp0_LevM1" on cells [0,1], the 2nd called "grp1_LevM1" on cells [0,1,2], and the 3rd called "grp2_LevM1" on cells [1,2,3] ::
- grp0_M1=ml.DataArrayInt.New([0,1]) ; grp0_M1.setName("grp0_LevM1")
- grp1_M1=ml.DataArrayInt.New([0,1,2]) ; grp1_M1.setName("grp1_LevM1")
- grp2_M1=ml.DataArrayInt.New([1,2,3]) ; grp2_M1.setName("grp2_LevM1")
+ grp0_M1=mc.DataArrayInt.New([0,1]) ; grp0_M1.setName("grp0_LevM1")
+ grp1_M1=mc.DataArrayInt.New([0,1,2]) ; grp1_M1.setName("grp1_LevM1")
+ grp2_M1=mc.DataArrayInt.New([1,2,3]) ; grp2_M1.setName("grp2_LevM1")
meshMEDFile.setGroupsAtLevel(-1,[grp0_M1,grp1_M1,grp2_M1])
Then trying to read it. ::
- meshMEDFileRead=ml.MEDFileMesh.New("TargetMesh2.med")
+ meshMEDFileRead=mc.MEDFileMesh.New("TargetMesh2.med")
meshRead0=meshMEDFileRead.getMeshAtLevel(0)
meshRead1=meshMEDFileRead.getMeshAtLevel(-1)
print("Is the mesh at level 0 read in file equals targetMesh ? %s"%(meshRead0.isEqual(targetMesh,1e-12)))
Creation of a simple vector field on cells called f. ::
- f=ml.MEDCouplingFieldDouble.New(ml.ON_CELLS,ml.ONE_TIME)
+ f=mc.MEDCouplingFieldDouble.New(mc.ON_CELLS,mc.ONE_TIME)
f.setTime(5.6,7,8)
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
Put f into a MEDFileField1TS for preparation of MED writing ::
- fMEDFile=ml.MEDFileField1TS.New()
+ fMEDFile=mc.MEDFileField1TS.New()
fMEDFile.setFieldNoProfileSBT(f)
Append field to "TargetMesh2.med" ::
Read it : ::
- fMEDFileRead=ml.MEDFileField1TS.New("TargetMesh2.med",f.getName(),7,8)
- fRead1=fMEDFileRead.getFieldOnMeshAtLevel(ml.ON_CELLS,0,meshMEDFileRead) # fastest method. No reading of the supporting mesh.
- fRead2=fMEDFileRead.getFieldAtLevel(ml.ON_CELLS,0) # like above but mesh is re-read from file...
+ fMEDFileRead=mc.MEDFileField1TS.New("TargetMesh2.med",f.getName(),7,8)
+ fRead1=fMEDFileRead.getFieldOnMeshAtLevel(mc.ON_CELLS,0,meshMEDFileRead) # fastest method. No reading of the supporting mesh.
+ fRead2=fMEDFileRead.getFieldAtLevel(mc.ON_CELLS,0) # like above but mesh is re-read from file...
print("Does the field f remain the same using fast method ? %s"%(fRead1.isEqual(f,1e-12,1e-12)))
print("Does the field f remain the same using slow method ? %s"%(fRead2.isEqual(f,1e-12,1e-12)))
Build a reduction on cells [1,2,3] of f and call it fPart. ::
- pfl=ml.DataArrayInt.New([1,2,3]) ; pfl.setName("My1stPfl")
+ pfl=mc.DataArrayInt.New([1,2,3]) ; pfl.setName("My1stPfl")
fPart=f.buildSubPart(pfl)
fPart.setName("fPart")
Put it into MEDFileField1TS data structure. ::
- fMEDFile2=ml.MEDFileField1TS.New()
+ fMEDFile2=mc.MEDFileField1TS.New()
fMEDFile2.setFieldProfile(fPart,meshMEDFileRead,0,pfl)
fMEDFile2.write("TargetMesh2.med",0) # 0 is very important here because we want to append to TargetMesh2.med and not to scratch it
Read "fPart" field from File "TargetMesh2.med". ::
- fMEDFileRead2=ml.MEDFileField1TS.New("TargetMesh2.med",fPart.getName(),7,8)
- fPartRead,pflRead=fMEDFileRead2.getFieldWithProfile(ml.ON_CELLS,0,meshMEDFileRead)
+ fMEDFileRead2=mc.MEDFileField1TS.New("TargetMesh2.med",fPart.getName(),7,8)
+ fPartRead,pflRead=fMEDFileRead2.getFieldWithProfile(mc.ON_CELLS,0,meshMEDFileRead)
print(fPartRead.isEqualWithoutConsideringStr(fPart.getArray(),1e-12))
print(pflRead.isEqualWithoutConsideringStr(pfl))
~~~~~~~~~~~~~~~~~~~~~~
Cet exercice repose comme tous les autres sur le language de script Python. On charge
-le module Python ``MEDLoader``.
+le module Python ``medcoupling``.::
-Pour information, le module ``MEDCoupling`` complet est inclus dans ``MEDLoader``. Pas besoin de l'importer
-si ``MEDLoader`` a été chargé. ::
-
- import MEDLoader as ml
+ import medcoupling as mc
Lecture, écriture d'un maillage
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
targetCoords = [-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn = [0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh = ml.MEDCouplingUMesh("MyMesh",2)
+ targetMesh = mc.MEDCouplingUMesh("MyMesh",2)
targetMesh.allocateCells(5)
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[4:7])
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[7:10])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[0:4])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[10:14])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[14:18])
- myCoords = ml.DataArrayDouble(targetCoords,9,2)
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
+ myCoords = mc.DataArrayDouble(targetCoords,9,2)
myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
targetMesh.setCoords(myCoords)
On peut alors écrire les deux maillages dans le fichier "TargetMesh2.med". ::
- meshMEDFile = ml.MEDFileUMesh()
+ meshMEDFile = mc.MEDFileUMesh()
meshMEDFile.setMeshAtLevel(0,targetMesh)
meshMEDFile.setMeshAtLevel(-1,targetMesh1)
meshMEDFile.write("TargetMesh2.med",2) # 2 stands for 'write from scratch'
correspond à la 1D, etc ...). Le premier groupe ``grp0_Lev0`` contient les cellules [0,1,3]
le second ``grp1_Lev0`` les cellules [1,2,3,4] : ::
- grp0_0 = ml.DataArrayInt([0,1,3])
+ grp0_0 = mc.DataArrayInt([0,1,3])
grp0_0.setName("grp0_Lev0")
- grp1_0 = ml.DataArrayInt([1,2,3,4])
+ grp1_0 = mc.DataArrayInt([1,2,3,4])
grp1_0.setName("grp1_Lev0")
meshMEDFile.setGroupsAtLevel(0, [grp0_0,grp1_0])
``grp0_LevM1`` aux cellules [0,1], le second appelé ``grp1_LevM1`` aux cellules [0,1,2], et le 3ème ``grp2_LevM1``
aux cellules [1,2,3] : ::
- grp0_M1 = ml.DataArrayInt([0,1])
+ grp0_M1 = mc.DataArrayInt([0,1])
grp0_M1.setName("grp0_LevM1")
- grp1_M1 = ml.DataArrayInt([0,1,2])
+ grp1_M1 = mc.DataArrayInt([0,1,2])
grp1_M1.setName("grp1_LevM1")
- grp2_M1 = ml.DataArrayInt([1,2,3])
+ grp2_M1 = mc.DataArrayInt([1,2,3])
grp2_M1.setName("grp2_LevM1")
meshMEDFile.setGroupsAtLevel(-1,[grp0_M1,grp1_M1,grp2_M1])
Nous pouvons ensuite re-lire le fichier MED : ::
- meshMEDFileRead = ml.MEDFileMesh.New("TargetMesh2.med") # a new is needed because it returns a MEDFileUMesh (MEDFileMesh is abstract)
+ meshMEDFileRead = mc.MEDFileMesh.New("TargetMesh2.med") # a new is needed because it returns a MEDFileUMesh (MEDFileMesh is abstract)
meshRead0 = meshMEDFileRead.getMeshAtLevel(0)
meshRead1 = meshMEDFileRead.getMeshAtLevel(-1)
print("Is level 0 in the file equal to 'targetMesh'?", meshRead0.isEqual(targetMesh,1e-12))
Créons un champ de vecteurs simple, aux cellules (P0), avec un seul pas de temps, appelé ``f``. ::
- f = ml.MEDCouplingFieldDouble(ml.ON_CELLS, ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble(mc.ON_CELLS, mc.ONE_TIME)
f.setTime(5.6,7,8)
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
Stocker ``f`` dans un object ``MEDFileField1TS`` (un champ avec un seul pas de temps -- *one time-step, 1TS*)
pour préparer l'écriture MED ::
- fMEDFile = ml.MEDFileField1TS()
+ fMEDFile = mc.MEDFileField1TS()
fMEDFile.setFieldNoProfileSBT(f) # No profile desired on the field, Sort By Type
Ajouter le champ au fichier "TargetMesh2.med" ::
Lire le champ : ::
- fMEDFileRead = ml.MEDFileField1TS("TargetMesh2.med",f.getName(),7,8)
- fRead1 = fMEDFileRead.getFieldOnMeshAtLevel(ml.ON_CELLS,0,meshMEDFileRead) # Quickest way, not re-reading mesh in the file.
- fRead2 = fMEDFileRead.getFieldAtLevel(ml.ON_CELLS,0) # Like above, but this time the mesh is read!
+ fMEDFileRead = mc.MEDFileField1TS("TargetMesh2.med",f.getName(),7,8)
+ fRead1 = fMEDFileRead.getFieldOnMeshAtLevel(mc.ON_CELLS,0,meshMEDFileRead) # Quickest way, not re-reading mesh in the file.
+ fRead2 = fMEDFileRead.getFieldAtLevel(mc.ON_CELLS,0) # Like above, but this time the mesh is read!
print("Does the field remain OK with the quick method?", fRead1.isEqual(f,1e-12,1e-12))
print("Does the field remain OK with the slow method?", fRead2.isEqual(f,1e-12,1e-12))
Construisons une réduction aux cellules [1,2,3] de ``f`` et appelons la ``fPart`` : ::
- pfl = ml.DataArrayInt([1,2,3])
+ pfl = mc.DataArrayInt([1,2,3])
pfl.setName("My1stPfl")
fPart = f.buildSubPart(pfl)
fPart.setName("fPart")
La stocker dans la structure ``MEDFileField1TS`` et invoquer ``setFieldProfile()``. ::
- fMEDFile2 = ml.MEDFileField1TS()
+ fMEDFile2 = mc.MEDFileField1TS()
fMEDFile2.setFieldProfile(fPart,meshMEDFileRead,0,pfl) # 0 is the relative level (here 0 means 2D)
fMEDFile2.write("TargetMesh2.med",0) # 0 is paramount to indicate that we *append* (and no overwrite) to the MED file
Lire le champ ``fPart`` du fichier "TargetMesh2.med" et les identifiants de cellules correspondant. ::
- fMEDFileRead2 = ml.MEDFileField1TS("TargetMesh2.med",fPart.getName(),7,8)
- fPartRead, pflRead = fMEDFileRead2.getFieldWithProfile(ml.ON_CELLS,0,meshMEDFileRead)
+ fMEDFileRead2 = mc.MEDFileField1TS("TargetMesh2.med",fPart.getName(),7,8)
+ fPartRead, pflRead = fMEDFileRead2.getFieldWithProfile(mc.ON_CELLS,0,meshMEDFileRead)
print("Is the partial field correctly read?", fPartRead.isEqualWithoutConsideringStr(fPart.getArray(),1e-12))
print("Is the list of cell identifiers matching?", pflRead.isEqualWithoutConsideringStr(pfl))
Implementation start
~~~~~~~~~~~~~~~~~~~~
-To implement this exercise we use the Python scripting language and import the MEDLoader Python module.
-The whole MEDCoupling module is fully included in MEDLoader. No need to import MEDCoupling when MEDLoader has been loaded. ::
+To implement this exercise we use the Python scripting language and import the `medcoupling` Python module. ::
- import MEDLoader as ml
+ import medcoupling as mc
Writing/Reading a mesh
~~~~~~~~~~~~~~~~~~~~~~
targetCoords=[-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn=[0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh=ml.MEDCouplingUMesh.New("MyMesh",2)
+ targetMesh=mc.MEDCouplingUMesh.New("MyMesh",2)
targetMesh.allocateCells(5)
targetMesh.insertNextCell(NORM_TRI3,3,targetConn[4:7])
targetMesh.insertNextCell(NORM_TRI3,3,targetConn[7:10])
targetMesh.insertNextCell(NORM_QUAD4,4,targetConn[0:4])
targetMesh.insertNextCell(NORM_QUAD4,4,targetConn[10:14])
targetMesh.insertNextCell(NORM_QUAD4,4,targetConn[14:18])
- myCoords=ml.DataArrayDouble.New(targetCoords,9,2)
+ myCoords=mc.DataArrayDouble.New(targetCoords,9,2)
myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
targetMesh.setCoords(myCoords)
We are then ready to write it. ::
- ml.WriteUMesh("TargetMesh.med",targetMesh,True)
+ mc.WriteUMesh("TargetMesh.med",targetMesh,True)
Then trying to read it. ::
- meshRead=ml.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
+ meshRead=mc.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
print("Is the mesh read in file equals targetMesh? %s"%(meshRead.isEqual(targetMesh,1e-12)))
Writing/Reading a field on one time step at once
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Creation of a vector field "f" on cell supported by "targetMesh". ::
- f=ml.MEDCouplingFieldDouble.New(ON_CELLS,ONE_TIME)
+ f=mc.MEDCouplingFieldDouble.New(ON_CELLS,ONE_TIME)
f.setTime(5.6,7,8)
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
f.setName("AFieldName")
- ml.WriteField("MyFirstField.med",f,True)
+ mc.WriteField("MyFirstField.med",f,True)
.. note:: Mesh AND Field is written at once into MyFirstField.
Reading into MyFirstField.med ::
- f2=ml.ReadFieldCell("MyFirstField.med",f.getMesh().getName(),0,f.getName(),7,8)
+ f2=mc.ReadFieldCell("MyFirstField.med",f.getMesh().getName(),0,f.getName(),7,8)
print("Is the field read in file equals f ? %s"%(f2.isEqual(f,1e-12,1e-12)))
Writing/Reading a field on one or many times steps in "multi-session mode"
Here contrary to the previous steps, we are going to write in a multi-session mode on the same MED file.
First dealing with the mesh. ::
- ml.WriteUMesh("MySecondField.med",f.getMesh(),True)
+ mc.WriteUMesh("MySecondField.med",f.getMesh(),True)
Then writing only array part of field. ::
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f)
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f)
Then put a another time step. ::
f2=f.clone(True)
f2.getArray()[:]=2.0
f2.setTime(7.8,9,10)
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
Now "MySecondField.med" file contains 2 time steps.
~~~~~~~~~~~~~~~~~~~~~~
Cet exercice repose comme tous les autres sur le language de script Python. On charge
-le module Python ``MEDLoader``.
+le module Python ``medcoupling``.::
-Pour information, le module ``MEDCoupling`` complet est inclus dans ``MEDLoader``. Pas besoin de l'importer
-si ``MEDLoader`` a été chargé. ::
-
- import MEDLoader as ml
+ import medcoupling as mc
Lecture, écriture d'un maillage
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
targetCoords = [-0.3,-0.3, 0.2,-0.3, 0.7,-0.3, -0.3,0.2, 0.2,0.2, 0.7,0.2, -0.3,0.7, 0.2,0.7, 0.7,0.7 ]
targetConn = [0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
- targetMesh = ml.MEDCouplingUMesh("MyMesh",2)
+ targetMesh = mc.MEDCouplingUMesh("MyMesh",2)
targetMesh.allocateCells(5)
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[4:7])
- targetMesh.insertNextCell(ml.NORM_TRI3,3,targetConn[7:10])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[0:4])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[10:14])
- targetMesh.insertNextCell(ml.NORM_QUAD4,4,targetConn[14:18])
- myCoords = ml.DataArrayDouble(targetCoords,9,2)
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
+ targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
+ targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
+ myCoords = mc.DataArrayDouble(targetCoords,9,2)
myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
targetMesh.setCoords(myCoords)
Le maillage peut alors directement être écrit ... ::
- ml.WriteUMesh("TargetMesh.med",targetMesh,True) # True means 'from scratch'
+ mc.WriteUMesh("TargetMesh.med",targetMesh,True) # True means 'from scratch'
... et relu. ::
- meshRead = ml.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
+ meshRead = mc.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
print("Is the read mesh equal to 'targetMesh' ?", meshRead.isEqual(targetMesh,1e-12))
Lire/Ecrire un champ sur un pas de temps
que dans les champs MEDCoupling, le temps physique est donné pour information seulement, le stockage et la plupart des
fonctions de l'API se basent sur les deux derniers entiers. ::
- f = ml.MEDCouplingFieldDouble.New(ml.ON_CELLS, ml.ONE_TIME)
+ f = mc.MEDCouplingFieldDouble.New(mc.ON_CELLS, mc.ONE_TIME)
f.setTime(5.6,7,8) # Declare the timestep associated to the field
f.setArray(targetMesh.computeCellCenterOfMass())
f.setMesh(targetMesh)
f.setName("AFieldName")
- ml.WriteField("MyFirstField.med",f,True)
+ mc.WriteField("MyFirstField.med",f,True)
Question subsidiaire : à quoi correspond le champ ainsi créé ?
Nous relisons ensuite MyFirstField.med : ::
- f2 = ml.ReadFieldCell("MyFirstField.med", f.getMesh().getName(), 0, f.getName(), 7, 8)
+ f2 = mc.ReadFieldCell("MyFirstField.med", f.getMesh().getName(), 0, f.getName(), 7, 8)
print("Is the read field identical to 'f' ?", f2.isEqual(f,1e-12,1e-12))
.. note:: Lors de la lecture du champ, on doit donc connaître: son nom, le nom de sa mesh de support
Ici contrairement au cas précédent, nous écrivons en plusieurs fois dans le *même* fichier MED.
Ecrivons tout d'abord le maillage. ::
- ml.WriteUMesh("MySecondField.med",f.getMesh(),True)
+ mc.WriteUMesh("MySecondField.med",f.getMesh(),True)
Ensuite, nous écrivons seulement les informations relatives au champ (principalement son tableau de valeurs en fait
). ::
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f) # mesh is not re-written
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f) # mesh is not re-written
Nous rajoutons ensuite un second pas de temps sur le *même* maillage. ::
f2 = f.clone(True) # 'True' means that we need a deep copy
f2.getArray()[:] = 2.0
f2.setTime(7.8,9,10)
- ml.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
+ mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
Maintenant le fichier "MySecondField.med" contient le maillage et un champ à deux pas de temps porté par ce maillage.
Nous pouvons relire tout cela avec des méthodes similaires à ce qui a été vu précédemment : ::
- f3 = ml.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),7,8)
+ f3 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),7,8)
print("Is the field read in file equals to 'f' ?", f.isEqual(f3,1e-12,1e-12))
- f4 = ml.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),9,10)
+ f4 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),9,10)
print("Is the field read in file equals to 'f2' ?", f2.isEqual(f4,1e-12,1e-12))
Solution