source: issm/branches/trunk-larour-NatGeoScience2016/scripts/BinRead.py@ 21758

Last change on this file since 21758 was 21758, checked in by Eric.Larour, 8 years ago

CHG: diverse

  • Property svn:executable set to *
File size: 5.9 KB
Line 
1#! /usr/bin/env python
2
3import os
4import sys
5import numpy
6import math
7import struct
8import argparse
9
10def BinRead(filin,filout='',verbose=0): #{{{
11
12 print "reading binary file."
13 f=open(filin,'rb')
14
15 if filout:
16 sys.stdout=open(filout,'w')
17
18 while True:
19 try:
20 #Step 1: read size of record name
21 recordnamesize=struct.unpack('i',f.read(struct.calcsize('i')))[0]
22 except struct.error as e:
23 print "probable EOF: %s" % e
24 break
25
26 print "============================================================================"
27 if verbose>2:
28 print "\nrecordnamesize = \"%d\"" % (recordnamesize)
29 recordname=struct.unpack('%ds' % recordnamesize,f.read(recordnamesize))[0]
30 print "field: %s" % recordname
31
32 #Step 2: read the data itself.
33 #first read length of record
34 reclen=struct.unpack('i',f.read(struct.calcsize('i')))[0]
35 if verbose>1:
36 print "reclen = %d" % reclen
37
38 #read data code:
39 code=struct.unpack('i',f.read(struct.calcsize('i')))[0]
40 #print "code = %d (%s)" % (code,CodeToFormat(code))
41 print "Format = %s" % CodeToFormat(code)
42
43 if code == FormatToCode('Boolean'):
44# bval=struct.unpack('b',f.read(reclen-struct.calcsize('i')))[0]
45 bval=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
46 print "value = %d" % bval
47
48 elif code == FormatToCode('Integer'):
49 ival=struct.unpack('i',f.read(reclen-struct.calcsize('i')))[0]
50 print "value = %d" % ival
51
52 elif code == FormatToCode('Double'):
53 dval=struct.unpack('d',f.read(reclen-struct.calcsize('i')))[0]
54 print "value = %f" % dval
55
56 elif code == FormatToCode('String'):
57 strlen=struct.unpack('i',f.read(struct.calcsize('i')))[0]
58 if verbose>1:
59 print "strlen = %d" % strlen
60 sval=struct.unpack('%ds' % strlen,f.read(strlen))[0]
61 print "value = '%s'" % sval
62
63 elif code == FormatToCode('BooleanMat'):
64 #read matrix type:
65 mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
66 print "mattype = %d" % mattype
67
68 #now read matrix
69 s=[0,0]
70 s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
71 s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
72 print "size = [%dx%d]" % (s[0],s[1])
73 data=numpy.zeros((s[0],s[1]))
74 for i in xrange(s[0]):
75 for j in xrange(s[1]):
76 data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0] #get to the "c" convention, hence the transpose
77 if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
78
79 elif code == FormatToCode('IntMat'):
80 #read matrix type:
81 mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
82 print "mattype = %d" % mattype
83
84 #now read matrix
85 s=[0,0]
86 s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
87 s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
88 print "size = [%dx%d]" % (s[0],s[1])
89 data=numpy.zeros((s[0],s[1]))
90 for i in xrange(s[0]):
91 for j in xrange(s[1]):
92 data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0] #get to the "c" convention, hence the transpose
93 if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
94
95 elif code == FormatToCode('DoubleMat'):
96 #read matrix type:
97 mattype=struct.unpack('i',f.read(struct.calcsize('i')))[0]
98 print "mattype = %d" % mattype
99
100 #now read matrix
101 s=[0,0]
102 s[0]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
103 s[1]=struct.unpack('i',f.read(struct.calcsize('i')))[0]
104 print "size = [%dx%d]" % (s[0],s[1])
105 data=numpy.zeros((s[0],s[1]))
106 for i in xrange(s[0]):
107 for j in xrange(s[1]):
108 data[i][j]=struct.unpack('d',f.read(struct.calcsize('d')))[0] #get to the "c" convention, hence the transpose
109 if verbose>2: print "data[%d,%d] = %f" % (i,j,data[i][j])
110
111 elif code == FormatToCode('MatArray'):
112 f.seek(reclen-4,1)
113 print "skipping %d bytes for code %d." % (code, reclen-4)
114
115 elif code == FormatToCode('StringArray'):
116 f.seek(reclen-4,1)
117 print "skipping %d bytes for code %d." % (code, reclen-4)
118
119 else:
120 raise TypeError('BinRead error message: data type: %d not supported yet! (%s)' % (code,recordname))
121
122 f.close()
123#}}}
124def FormatToCode(format): # {{{
125 """
126 This routine takes the format string, and hardcodes it into an integer, which
127 is passed along the record, in order to identify the nature of the dataset being
128 sent.
129 """
130
131 if format=='Boolean':
132 code=1
133 elif format=='Integer':
134 code=2
135 elif format=='Double':
136 code=3
137 elif format=='String':
138 code=4
139 elif format=='BooleanMat':
140 code=5
141 elif format=='IntMat':
142 code=6
143 elif format=='DoubleMat':
144 code=7
145 elif format=='MatArray':
146 code=8
147 elif format=='StringArray':
148 code=9
149 else:
150 raise InputError('FormatToCode error message: data type not supported yet!')
151
152 return code
153# }}}
154def CodeToFormat(code): # {{{
155 """
156 This routine takes the format string, and hardcodes it into an integer, which
157 is passed along the record, in order to identify the nature of the dataset being
158 sent.
159 """
160
161 if code==1:
162 format='Boolean'
163 elif code==2:
164 format='Integer'
165 elif code==3:
166 format='Double'
167 elif code==4:
168 format='String'
169 elif code==5:
170 format='BooleanMat'
171 elif code==6:
172 format='IntMat'
173 elif code==7:
174 format='DoubleMat'
175 elif code==8:
176 format='MatArray'
177 elif code==9:
178 format='StringArray'
179 else:
180 raise TypeError('FormatToCode error message: code %d not supported yet!' %code)
181
182 return format
183# }}}
184
185if __name__ == '__main__': #{{{
186 if 'PYTHONSTARTUP' in os.environ:
187 PYTHONSTARTUP=os.environ['PYTHONSTARTUP']
188 print 'PYTHONSTARTUP =',PYTHONSTARTUP
189 if os.path.exists(PYTHONSTARTUP):
190 try:
191 execfile(PYTHONSTARTUP)
192 except Exception as e:
193 print "PYTHONSTARTUP error: ",e
194 else:
195 print "PYTHONSTARTUP file '%s' does not exist." % PYTHONSTARTUP
196
197 parser = argparse.ArgumentParser(description='BinRead - function to read binary input file.')
198 parser.add_argument('-f','--filin', help='name of binary input file', default='')
199 parser.add_argument('-o','--filout', help='optional name of text output file', default='')
200 parser.add_argument('-v','--verbose', help='optional level of output', default=0)
201 args = parser.parse_args()
202
203 BinRead(args.filin, args.filout,args.verbose)
204#}}}
Note: See TracBrowser for help on using the repository browser.