DMelt:IO/Saving Arrays
Multi-dimensional arrays
Arrays in 1,2,3,4,5 dimensions can be written in a binary form to files and later restored. Unlike the standard Java serialization, we will consider a binary form for such arrays.
Input and Output for 1D and 2D array
The easiest way to store 1D arrays of double values in a compact binary form is to use jhplot.math.DoubleArray or jhplot.math.IntegerArray (for integers) and then use the class jhplot.math.io.ASCIIFile to write and read such arrays.
Here is a small example:
from jhplot.math.DoubleArray import * from jhplot.math.io.ASCIIFile import * a =[1.0, 2.0, 3.0, 4.0] b =[ [1.0, 2.0, 3.0, 4.0], [11.0, 12.0, 13.0, 14.0] ] writeDoubleArray(File("a.txt"), a) # write files in ASCII writeDoubleArray(File("b.txt"), b) a_read = readDouble1DArray(File("a.txt")) # reading arrays b_read = readDoubleArray(File("b.txt")) print "a_read = \n" + printDoubleArray(a_read) # now print print "b_read = \n" + printDoubleArray(b_read)
Large arrays can be written in the binary form:
from jhplot.math.DoubleArray import * from jhplot.math.io.BinaryFile import * a =[1.0, 2.0, 3.0, 4.0] writeDoubleArray(File("a.dat"), a, "LITTLE_ENDIAN") # write the array a_read = readDoubleArray(File("a.dat"), "LITTLE_ENDIAN") # read these file print "a_read from binary file = \n" + printDoubleArray(a_read)
2D arrays cannot be written in the binary form using this approach
Below we will consider a more general approach to write and read 1D, 2D, 3D, 4D and 5D arrays in the binary form.
I/O for 1D array
Use the class called jhplot.io.ArrayReaderWriter which can write and read arrays in multiple dimensions. Here is a small example for 1D arrays:
>> from jhplot.io import ArrayReaderWriter >> ArrayReaderWriter.write([1.0,2.0,3.0,4.0,],"test.d") >> b=ArrayReaderWriter.read1DArray("test.d") >> print b array('d', [1.0, 2.0, 3.0, 4.0])
I/O for 2D array
jhplot.io.ArrayReaderWriter which can write and read arrays in multiple dimensions. Here is a small example for 1D arrays:
>> from jhplot.io import ArrayReaderWriter >> ArrayReaderWriter.write([[1.0,2.0],[1,2],"test.d") >> b=ArrayReaderWriter.read2DArray("test.d") # read it back
I/O of 3D array
I/O of 4D array