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