-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathtypes.py
317 lines (239 loc) · 7.87 KB
/
types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Conversions to and from bytes representation of values in TDMS files"""
import numpy as np
import struct
from nptdms.timestamp import TdmsTimestamp, TimestampArray
from nptdms.log import log_manager
log = log_manager.get_logger(__name__)
__all__ = [
'numpy_data_types',
'tds_data_types',
'TdmsType',
'Bytes',
'Void',
'Int8',
'Int16',
'Int32',
'Int64',
'Uint8',
'Uint16',
'Uint32',
'Uint64',
'SingleFloat',
'DoubleFloat',
'ExtendedFloat',
'SingleFloatWithUnit',
'DoubleFloatWithUnit',
'ExtendedFloatWithUnit',
'String',
'Boolean',
'TimeStamp',
'ComplexSingleFloat',
'ComplexDoubleFloat',
'DaqMxRawData',
]
_struct_pack = struct.pack
_struct_unpack = struct.unpack
tds_data_types = {}
numpy_data_types = {}
def tds_data_type(enum_value, np_type, set_np_type=True):
def decorator(cls):
cls.enum_value = enum_value
cls.nptype = None if np_type is None else np.dtype(np_type)
if enum_value is not None:
tds_data_types[enum_value] = cls
if set_np_type and np_type is not None:
numpy_data_types[np.dtype(np_type)] = cls
return cls
return decorator
class TdmsType(object):
size = None
def __init__(self):
self.value = None
self.bytes = None
def __eq__(self, other):
return self.bytes == other.bytes and self.value == other.value
def __repr__(self):
if self.value is None:
return "%s" % self.__class__.__name__
return "%s(%r)" % (self.__class__.__name__, self.value)
@classmethod
def read(cls, file, endianness="<"):
raise NotImplementedError("Unsupported data type to read: %r" % cls)
@classmethod
def read_values(cls, file, number_values, endianness="<"):
raise NotImplementedError("Unsupported data type to read: %r" % cls)
class Bytes(TdmsType):
def __init__(self, value):
self.value = value
self.bytes = value
class StructType(TdmsType):
struct_declaration = None
nptype = None
def __init__(self, value):
self.value = value
self.bytes = _struct_pack('<' + self.struct_declaration, value)
@classmethod
def read(cls, file, endianness="<"):
read_bytes = file.read(cls.size)
return _struct_unpack(endianness + cls.struct_declaration, read_bytes)[0]
@classmethod
def from_bytes(cls, byte_array, endianness="<"):
""" Convert an array of bytes into a numpy array of data
"""
array = byte_array.view()
array.dtype = cls.nptype.newbyteorder(endianness)
return array
@tds_data_type(0, None)
class Void(TdmsType):
pass
@tds_data_type(1, np.int8)
class Int8(StructType):
size = 1
struct_declaration = "b"
@tds_data_type(2, np.int16)
class Int16(StructType):
size = 2
struct_declaration = "h"
@tds_data_type(3, np.int32)
class Int32(StructType):
size = 4
struct_declaration = "l"
@tds_data_type(4, np.int64)
class Int64(StructType):
size = 8
struct_declaration = "q"
@tds_data_type(5, np.uint8)
class Uint8(StructType):
size = 1
struct_declaration = "B"
@tds_data_type(6, np.uint16)
class Uint16(StructType):
size = 2
struct_declaration = "H"
@tds_data_type(7, np.uint32)
class Uint32(StructType):
size = 4
struct_declaration = "L"
@tds_data_type(8, np.uint64)
class Uint64(StructType):
size = 8
struct_declaration = "Q"
@tds_data_type(9, np.single)
class SingleFloat(StructType):
size = 4
struct_declaration = "f"
@tds_data_type(10, np.double)
class DoubleFloat(StructType):
size = 8
struct_declaration = "d"
@tds_data_type(11, None)
class ExtendedFloat(TdmsType):
pass
@tds_data_type(0x19, np.single, set_np_type=False)
class SingleFloatWithUnit(StructType):
size = 4
struct_declaration = "f"
@tds_data_type(0x1A, np.double, set_np_type=False)
class DoubleFloatWithUnit(StructType):
size = 8
struct_declaration = "d"
@tds_data_type(0x1B, None)
class ExtendedFloatWithUnit(TdmsType):
pass
@tds_data_type(0x20, None)
class String(TdmsType):
def __init__(self, value):
self.value = value
content = value.encode('utf-8')
length = _struct_pack('<L', len(content))
self.bytes = length + content
@staticmethod
def read(file, endianness="<"):
size_bytes = file.read(4)
size = _struct_unpack(endianness + 'L', size_bytes)[0]
return String._decode(file.read(size))
@classmethod
def read_values(cls, file, number_values, endianness="<"):
""" Read string raw data
This is stored as an array of offsets
followed by the contiguous string data.
"""
offsets = [0]
for i in range(number_values):
offsets.append(Uint32.read(file, endianness))
strings = []
for i in range(number_values):
s = file.read(offsets[i + 1] - offsets[i])
strings.append(String._decode(s))
return strings
@staticmethod
def _decode(string_bytes):
try:
return string_bytes.decode('utf-8')
except UnicodeDecodeError as exc:
log.warning(
"Error decoding string from bytes %s, retrying with replace handler: %s",
string_bytes, exc)
return string_bytes.decode('utf-8', errors='replace')
@tds_data_type(0x21, np.bool_)
class Boolean(StructType):
size = 1
struct_declaration = "b"
def __init__(self, value):
self.value = bool(value)
self.bytes = _struct_pack('<' + self.struct_declaration, self.value)
@classmethod
def read(cls, file, endianness="<"):
return bool(super(Boolean, cls).read(file, endianness))
@tds_data_type(0x44, None)
class TimeStamp(TdmsType):
# Time stamps are stored as number of seconds since
# 01/01/1904 00:00:00.00 UTC, ignoring leap seconds,
# and number of 2^-64 fractions of a second.
# Note that the TDMS epoch is not the Unix epoch.
_tdms_epoch = np.datetime64('1904-01-01 00:00:00', 'us')
_fractions_per_microsecond = float(10**-6) / 2**-64
size = 16
def __init__(self, value):
if not isinstance(value, np.datetime64):
value = np.datetime64(value, 'us')
self.value = value
epoch_delta = value - self._tdms_epoch
seconds = int(epoch_delta / np.timedelta64(1, 's'))
remainder = epoch_delta - np.timedelta64(seconds, 's')
zero_delta = np.timedelta64(0, 's')
if remainder < zero_delta:
remainder = np.timedelta64(1, 's') + remainder
seconds = seconds - 1
microseconds = int(remainder / np.timedelta64(1, 'us'))
second_fractions = int(microseconds * self._fractions_per_microsecond)
self.bytes = _struct_pack('<Qq', second_fractions, seconds)
@classmethod
def read(cls, file, endianness="<"):
data = file.read(16)
if endianness == "<":
(second_fractions, seconds) = _struct_unpack(
endianness + 'Qq', data)
else:
(seconds, second_fractions) = _struct_unpack(
endianness + 'qQ', data)
return TdmsTimestamp(seconds, second_fractions)
@classmethod
def from_bytes(cls, byte_array, endianness="<"):
""" Convert an array of bytes to an array of timestamps
"""
byte_array = byte_array.reshape((-1, 16))
if endianness == "<":
dtype = np.dtype([('second_fractions', '<u8'), ('seconds', '<i8')])
else:
dtype = np.dtype([('seconds', '>i8'), ('second_fractions', '>u8')])
return TimestampArray(byte_array.view(dtype).reshape(-1))
@tds_data_type(0x08000c, np.complex64)
class ComplexSingleFloat(TdmsType):
size = 8
@tds_data_type(0x10000d, np.complex128)
class ComplexDoubleFloat(TdmsType):
size = 16
@tds_data_type(0xFFFFFFFF, None)
class DaqMxRawData(TdmsType):
pass