diff -r b930440af354 -r de9122b5680a HP3562A/__init__.py --- a/HP3562A/__init__.py Tue Dec 18 00:38:33 2007 +0100 +++ b/HP3562A/__init__.py Wed Dec 19 00:19:25 2007 +0100 @@ -15,27 +15,46 @@ import struct import re import gpib +import numpy ######################################## # HP3562A internal binary types decoders def decode_float(s): - assert len(s) in [4,8] - # exponential term - e = ord(s[-1]) - if e & 0x80: - e = e - 256 + if len(s) == 4: + i1, i2, e = struct.unpack('>hbb', s) + i2 = i2 * 2**(-23) + return (i1/32768. + i2)*2**e + else: + i1, i2, i3, i4, e = struct.unpack('>hhhbb', s) + if i2 < 0: + i2 = (i2+32768.)*2**(-15) + else: + i2 = i2*2**(-15) + if i3 < 0: + i3 = (i3+32768.)*2**(-30) + else: + i3 = i3*2**(-15) + i4 = i4 * 2**(-38) + return (i1+i2+i3+i4)*2**(e-15) + +# def decode_float(s): +# assert len(s) in [4,8] +# # exponential term +# e = ord(s[-1]) +# if e & 0x80: +# e = e - 256 - # mantissa - m = [ord(x) for x in s[:-1]] - M = 0. - for i in range(len(s)-1): - #M += m[i]<<(i*8) - M += float(m[i])/2**((i+1)*8) - # XXX how do we deal negative numbers? - #if m[0] & 0x80: - # M = M - 2^(len(s)) - return M * 2**(e+1) +# # mantissa +# m = [ord(x) for x in s[:-1]] +# M = 0. +# for i in range(len(s)-1): +# #M += m[i]<<(i*8) +# M += float(m[i])/2**((i+1)*8) +# # XXX how do we deal negative numbers? +# #if m[0] & 0x80: +# # M = M - 2^(len(s)) +# return M * 2**(e+1) def decode_string(s): nb = ord(s[0]) @@ -59,6 +78,8 @@ for row in head_struct: key = row[0] typ = row[1] + if typ is None: + continue val = header.get(key, "N/A") if isinstance(val, basestring): val = repr(val) @@ -83,23 +104,31 @@ fmt = "%%-%ds %%-%ds"%(maxk, maxv) w = maxk+maxv+4 ncols = columns/w - nrows = len(todisp)/ncols + if ncols: + nrows = len(todisp)/ncols + else: + nrows = len(todisp) res = "" for i in range(nrows): res += "| ".join([fmt%todisp[j*nrows+i] for j in range(ncols)]) + "\n" return res -def decode_header(data, header_struct): +def decode_header(data, header_struct, idx=0): d = data - typ = d[:2] - assert typ == "#A" - - totlen = struct.unpack('>h', d[2:4])[0] - idx = 4 + if d[idx:].startswith('#'): + # we have a preliminary header here... + typ = d[idx:idx+2] + assert typ == "#A" + idx += 2 + totlen = struct.unpack('>h', d[idx:idx+2])[0] + idx += 2 tt=0 header = {} for i, (nam, dtype, fmt, nbytes) in enumerate(header_struct): - if dtype == str: + if dtype is None: + idx += nbytes + continue + elif dtype == str: val = decode_string(d[idx:]) else: if fmt: @@ -114,6 +143,14 @@ idx += nbytes return header, idx +def read_trace(data, idx, nelts): + assert len(data[idx:]) >= (nelts*4), "data[idx:] is too small (%s for %s)"%(len(data[idx:]), (nelts*4)) + resu = [] + for i in range(nelts): + resu.append(decode_float(data[idx: idx+4])) + idx += 4 + return numpy.array(resu, dtype=float) + ##################### # HP3562A constants