I have a binary file with data stored as matrices. How can I access the data using human readable format using python?
-
1Do you know which format is used in the binary file? Which programs can open it?Andriy Makukha– Andriy Makukha2018-02-08 05:43:14 +00:00Commented Feb 8, 2018 at 5:43
-
MDAnalysis and MDtraj can both offer access to the data. The data can be parsed using the above two packages but I am wondering if it is worth writing a python code myself to do this. To be more specific, I am running a Molecular Dynamics simulation and dumping the coordinates of particles as binary data. The data can be parsed as numpy arrays of shape (N,3) where N is the number of particles and the columns are the x,y,z coordinates.Abhijit Ghosh– Abhijit Ghosh2018-02-09 06:35:27 +00:00Commented Feb 9, 2018 at 6:35
Add a comment
|
1 Answer
Both MDtraj and MDAnalysis are Python libraries with open code. That means, that it's probably not worth to spend time writing your own code to read any specific binary format. You can just use existing code from those libraries.
However, if you want to store those (N,3) numpy arrays in human readable format, you can use numpy.savetxt() and numpy.loadtxt() functions.
For example:
import numpy
# Create a matrix of size (N, 3)
N = 5
a = numpy.arange(N*3)
a.shape = (N,3)
# Save in human readable format
numpy.savetxt('matrix.txt', a, fmt='%g', delimiter='\t')
# Load from file
b = numpy.loadtxt('matrix.txt')
Contents of matrix.txt:
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
It will work with float numbers also.
2 Comments
Abhijit Ghosh
Thanks, this was helpful. I am using mdtraj for parsing; for some reasons it scales every coordinate by a factor of 10. Having corrected for this, I am now happy using mdtraj.
Andriy Makukha
@AbhijitGhosh, it's my pleasure to help. I will be also grateful if you choose my answer as the "best answer". Thanks.