2 .. _python_testMEDLoaderBasicAPI1_solution:
4 Reading, Writing a MED file using MEDLoader basic API
5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
9 import medcoupling as mc
11 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 ]
12 targetConn = [0,3,4,1, 1,4,2, 4,5,2, 6,7,4,3, 7,8,5,4]
13 targetMesh = mc.MEDCouplingUMesh("MyMesh",2)
14 targetMesh.allocateCells(5)
15 targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[4:7])
16 targetMesh.insertNextCell(mc.NORM_TRI3,3,targetConn[7:10])
17 targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[0:4])
18 targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[10:14])
19 targetMesh.insertNextCell(mc.NORM_QUAD4,4,targetConn[14:18])
20 myCoords = mc.DataArrayDouble(targetCoords,9,2)
21 myCoords.setInfoOnComponents(["X [km]","YY [mm]"])
22 targetMesh.setCoords(myCoords)
24 mc.WriteUMesh("TargetMesh.med",targetMesh,True) # True means 'from scratch'
25 # Re-read it and test equality
26 meshRead = mc.ReadUMeshFromFile("TargetMesh.med",targetMesh.getName(),0)
27 print("Is the read mesh equal to 'targetMesh' ?", meshRead.isEqual(targetMesh,1e-12))
28 # Writing a field and its support mesh in one go
29 f = mc.MEDCouplingFieldDouble.New(mc.ON_CELLS, mc.ONE_TIME)
30 f.setTime(5.6,7,8) # Declare the timestep associated to the field
31 f.setArray(targetMesh.computeCellCenterOfMass())
33 f.setName("AFieldName")
34 mc.WriteField("MyFirstField.med",f,True)
35 # Re-read it and test equality
36 f2 = mc.ReadFieldCell("MyFirstField.med", f.getMesh().getName(), 0, f.getName(), 7, 8)
37 print("Is the read field identical to 'f' ?", f2.isEqual(f,1e-12,1e-12))
38 # Writing in several steps
39 mc.WriteUMesh("MySecondField.med",f.getMesh(),True)
40 mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f)
41 # A second field to write
42 f2 = f.clone(True) # 'True' means that we need a deep copy
43 f2.getArray()[:] = 2.0
45 mc.WriteFieldUsingAlreadyWrittenMesh("MySecondField.med",f2)
46 # Re-read and test this two-timestep field
47 f3 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),7,8)
48 print("Is the field read in file equals to 'f' ?", f.isEqual(f3,1e-12,1e-12))
49 f4 = mc.ReadFieldCell("MySecondField.med",f.getMesh().getName(),0,f.getName(),9,10)
50 print("Is the field read in file equals to 'f2' ?", f2.isEqual(f4,1e-12,1e-12))