forked from ratal/mdfreader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdf4reader.py
2127 lines (1927 loc) · 91.3 KB
/
mdf4reader.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
""" Measured Data Format file reader module for version 4.x.
Platform and python version
----------------------------------------
With Unix and Windows for python 2.6+ and 3.2+
:Author: `Aymeric Rateau <https://github.com/ratal/mdfreader>`__
Created on Thu Dec 10 12:57:28 2013
Dependencies
-------------------
- Python >2.6, >3.2 <http://www.python.org>
- Numpy >1.6 <http://numpy.scipy.org>
- bitarray to parse bits in not aligned bytes
- Sympy to convert channels with formula if needed
- zlib to uncompress data block if needed
Attributes
--------------
PythonVersion : float
Python version currently running, needed for compatibility of both python 2.6+ and 3.2+
mdf4reader module
--------------------------
"""
from __future__ import print_function
from numpy.core.records import fromstring, fromfile
from numpy import array, recarray, append, asarray, empty, zeros, dtype, where
from numpy import arange, right_shift, bitwise_and, all, diff, interp, reshape
from struct import Struct, pack
from struct import unpack as structunpack
from math import pow
from sys import version_info, exc_info, byteorder, stderr
from io import open # for python 3 and 2 consistency
try:
from .mdfinfo4 import info4, MDFBlock, ATBlock, IDBlock, HDBlock, DGBlock, CGBlock, CNBlock, MDFBlock, FHBlock, CommentBlock
from .mdf import mdf_skeleton
except:
from mdfinfo4 import info4, MDFBlock, ATBlock, IDBlock, HDBlock, DGBlock, CGBlock, CNBlock, MDFBlock, FHBlock, CommentBlock
from mdf import mdf_skeleton
from time import gmtime, strftime
from multiprocessing import Queue, Process
PythonVersion = version_info
PythonVersion = PythonVersion[0]
LINK = '<Q'
REAL = '<d'
BOOL = '<h'
UINT8 = '<B'
BYTE = '<c'
INT16 = '<h'
UINT16 = '<H'
UINT32 = '<I'
INT32 = '<i'
UINT64 = '<Q'
INT64 = '<q'
CHAR = '<c'
def DATABlock(record, parent_block, channelList=None, sortedFlag=True):
""" DATABlock converts raw data into arrays
Parameters
----------------
record : class
record class instance describing a channel group record
parent_block : class
MDFBlock class containing at least parent block header
channelList : list of str, optional
defines list of channels to only read, can be slow but saves memory, for big files
sortedFlag : bool, optional
flag to know if data block is sorted (only one Channel Group in block)
or unsorted (several Channel Groups identified by a recordID). As unsorted block can
contain CG records in random order, block is processed iteratively,
not in raw like sorted -> much slower reading
Returns
---------
a recarray containing the channels data
Notes
--------
This function will read DTBlock, RDBlock, DZBlock (compressed), RDBlock (VLSD), sorted or unsorted
"""
if parent_block['id'] in ('##DT', '##RD', b'##DT', b'##RD'): # normal data block
if sortedFlag:
if channelList is None and not record.hiddenBytes and\
record.byte_aligned: # No channel list and length of records corresponds to C datatypes
return fromstring(parent_block['data'], dtype=record.numpyDataRecordFormat, shape=record.numberOfRecords, names=record.dataRecordName)
else: # record is not byte aligned or channelList not None
return record.readBitarray(parent_block['data'], channelList)
else: # unsorted reading
print('not implemented yet unsorted data block reading', file=stderr) # to be implemented if needed, missing example file
elif parent_block['id'] in ('##SD', b'##SD'):
if record.signalDataType == 6:
format = 'ISO8859'
elif record.signalDataType == 7:
format = 'utf-8'
elif record.signalDataType == 8:
format = '<utf-16'
elif record.signalDataType == 9:
format = '>utf-16'
pointer = 0
buf = [] # buf=array(record.numberOfRecords,dtype='s'+str(record.maxLengthVLSDRecord))
while pointer < parent_block['length'] - 24:
VLSDLen = structunpack('I', parent_block['data'][pointer:pointer + 4])[0] # length of data
pointer += 4
buf.append(parent_block['data'][pointer:pointer + VLSDLen].decode(format).rstrip('\x00')) # to be improved, removing append
# buf[nElement]=fid.read(VLSDLen).decode(format).rstrip('\x00')
pointer += VLSDLen
buf = equalizeStringLength(buf)
return array(buf)
elif parent_block['id'] in ('##DZ', b'##DZ'): # zipped data block
# uncompress data
parent_block['data'] = decompress_datablock(parent_block['data'], parent_block['dz_zip_type'],
parent_block['dz_zip_parameter'], parent_block['dz_org_data_length'])
if channelList is None and sortedFlag: # reads all blocks if sorted block and no channelList defined
if record.byte_aligned and not record.hiddenBytes:
record.numberOfRecords = parent_block['dz_org_data_length'] // record.CGrecordLength
return fromstring(parent_block['data'], dtype=record.numpyDataRecordFormat, shape=record.numberOfRecords, names=record.dataRecordName)
else:
return record.readBitarray(parent_block['data'], channelList)
elif channelList is not None and sortedFlag: # sorted data but channel list requested
return record.readBitarray(parent_block['data'], channelList)
else: # unsorted reading
# reads only the channels using offset functions, channel by channel.
buf = {}
position = 0
recordIdCFormat = record[list(record.keys())[0]]['record'].recordIDCFormat
recordIDsize = record[list(record.keys())[0]]['record'].recordIDsize
VLSDStruct = Struct('I')
# initialise data structure
for recordID in record:
for channelName in record[recordID]['record'].channelNames:
buf[channelName] = [] # empty(record.numberOfRecords,dtype=record[recordID]['record'].dataFormat)
# index[channelName]=0
# read data
while position < len(parent_block['data']):
recordID = recordIdCFormat.unpack(parent_block['data'][position:position + recordIDsize])[0]
if not record[recordID]['record'].Flags & 0b1: # not VLSD CG)
temp = record.readRecord(recordID, parent_block['data'][position:position + record[recordID]['record'].CGrecordLength + 1], channelList)
position += record[recordID]['record'].CGrecordLength
for channelName in temp:
buf[channelName].append(temp[channelName]) # to remove append
# buf[channelName][index[recordID]]=temp[channelName]
# index[recordID] += 1
else: # VLSD CG
position += recordIDsize
VLSDLen = VLSDStruct.unpack(parent_block['data'][position:position + 4])[0] # VLSD length
position += 4
temp = parent_block['data'][position:position + VLSDLen - 1]
if record[recordID]['record'].VLSD_CG[recordID]['channel'].signalDataType == 6:
temp = temp.decode('ISO8859')
elif record[recordID]['record'].VLSD_CG[recordID]['channel'].signalDataType == 7:
temp = temp.decode('utf-8')
elif record[recordID]['record'].VLSD_CG[recordID]['channel'].signalDataType == 8:
temp = temp.decode('<utf-16')
elif record[recordID]['record'].VLSD_CG[recordID]['channel'].signalDataType == 9:
temp = temp.decode('>utf-16')
buf[record[recordID]['record'].VLSD_CG[recordID]['channelName']].append(temp)
position += VLSDLen
# convert list to array
for chan in buf:
buf[chan] = array(buf[chan])
return buf
def decompress_datablock(block, zip_type, zip_parameter, org_data_length):
""" decompress datablock.
Parameters
--------------
block : bytes
raw data compressed
zip_type : int
0 for non transposed, 1 for transposed data
zip_parameter : int
first dimension of matrix to be transposed
org_data_length : int
uncompressed data length
Returns
---------
uncompressed raw data
"""
from zlib import decompress
if PythonVersion > 3: # decompress data
block = decompress(block)
else:
block = decompress(bytes(block)) # decompress data
if zip_type == 1: # data bytes transposed
M = org_data_length // zip_parameter
temp = array(memoryview(block[:M * zip_parameter]))
tail = array(memoryview(block[M * zip_parameter:]))
temp = temp.reshape(zip_parameter, M).T.ravel()
if len(tail) > 0:
temp = append(temp, tail)
block = temp.tostring()
return block
def equalizeStringLength(buf):
""" Makes all strings in a list having same length by appending spaces strings.
Parameters
----------------
buf : list of str
Returns
-----------
list of str elements all having same length
"""
maxlen = len(max(buf, key=len))
for i in range(len(buf)): # resize string to same length, numpy constrain
buf[i] += ' ' * (maxlen - len(buf[i]))
return buf
def append_field(rec, name, arr, numpy_dtype=None):
""" append new field in a recarray
Parameters
----------------
rec : numpy recarray
name : str
name of field to be appended
arr : numpy array to be appended
numpy_dtype : numpy dtype, optional
apply same dtype as arr by default but can be modified
Returns
-----------
numpy recarray appended
"""
arr = asarray(arr)
if numpy_dtype is None:
numpy_dtype = arr.dtype
newdtype = dtype(rec.dtype.descr + [(name, numpy_dtype)])
newrec = empty(rec.shape, dtype=newdtype)
for field in rec.dtype.fields:
newrec[field] = rec[field]
newrec[name] = arr
return newrec
def change_field_name(arr, old_name, new_name):
""" modifies name of field in a recarray
Parameters
----------------
arr : numpy recarray
old_name : str
old field
new_name : str
new field
Returns
-----------
numpy recarray with modified field name
"""
names = list(arr.dtype.names)
for n in range(len(names)):
if names[n] == old_name:
break
names[n] = new_name
names = tuple(names)
arr.dtype.names = names
return arr
def bits_to_bytes(nBits):
""" Converts number of bits into number of aligned bytes
Parameters
-------------
nBits : int
number of bits
Returns
----------
number of equivalent bytes
"""
if nBits <= 8:
nBytes = 1
elif nBits <= 16:
nBytes = 2
elif nBits <= 32:
nBytes = 4
elif nBits <= 64:
nBytes = 8
else:
nBytes = nBits // 8
if not nBits %8 == 0:
nBytes += 1
return nBytes
class DATA(dict):
""" DATA class is organizing record classes itself made of channel class.
This class inherits from dict. Keys are corresponding to channel group recordID
A DATA class corresponds to a data block, a dict of record classes (one per channel group)
Each record class contains a list of channel class representing the structure of channel record.
Attributes
--------------
fid : io.open
file identifier
pointerToData : int
position of Data block in mdf file
type : str
'sorted' or 'unsorted' data block
Methods
------------
addRecord(record)
Adds a new record in DATA class dict
read(channelList, zip=None)
Reads data block
load(record, zip=None, nameList=None)
Reads sorted data block from record definition
readRecord(recordID, buf, channelList=None):
read record from a buffer
"""
def __init__(self, fid, pointer):
""" Constructor
Parameters
----------------
fid : float
file identifier
pointer : int
position of data block in file
"""
self.fid = fid
self.pointerTodata = pointer
self.type = 'sorted'
def addRecord(self, record):
"""Adds a new record in DATA class dict.
Parameters
----------------
record class
channel group definition listing record channel classes
"""
self[record.recordID] = {}
self[record.recordID]['record'] = record
# detects VLSD CG
for recordID in self[record.recordID]['record'].VLSD_CG:
self[recordID]['record'].VLSD_CG = self[record.recordID]['record'].VLSD_CG
def read(self, channelList, zip=None):
"""Reads data block
Parameters
----------------
channelList : list of str
list of channel names
zip : bool, optional
flag to track if data block is compressed
"""
if len(self) == 1: # sorted dataGroup
recordID = list(self.keys())[0]
record = self[recordID]['record']
self[recordID]['data'] = self.load(record, zip=None, nameList=channelList, sortedFlag=True)
for cn in record.VLSD: # VLSD channels
if channelList is None or record[cn].name in channelList:
temp = DATA(self.fid, record[cn].data) # all channels
rec = self[recordID]['data'] # recarray from data block
# determine maximum length of values in VLSD for array dtype
# record[cn].maxLengthVLSDRecord=max(diff(rec[convertName(record[cn].name)])-4)
temp = temp.load(record[cn], zip=None, nameList=channelList, sortedFlag=True)
rec = change_field_name(rec, convertName(record[cn].name), convertName(record[cn].name) + '_offset')
rec = append_field(rec, convertName(record[cn].name), temp)
self[recordID]['data'] = rec.view(recarray)
else: # unsorted DataGroup
self.type = 'unsorted'
data = self.load(self, zip=None, nameList=channelList, sortedFlag=False)
for recordID in list(self.keys()):
self[recordID]['data'] = {}
for channel in self[recordID]['record']:
self[recordID]['data'][convertName(channel.name)] = data[channel.name]
def load(self, record, zip=None, nameList=None, sortedFlag=True): # reads sorted data
"""Reads data block from record definition
Parameters
----------------
record class
channel group definition listing record channel classes
zip : bool, optional
flag to track if data block is compressed
nameList : list of str, optional
list of channel names
Returns
-----------
numpy recarray of data
"""
temps = MDFBlock()
# block header
temps.loadHeader(self.fid, self.pointerTodata)
if temps['id'] in ('##DL', b'##DL'): # data list block
# link section
temps['dl_dl_next'] = temps.mdfblockread(self.fid, LINK, 1)
temps['dl_data'] = {}
temps['dl_data'][0] = [temps.mdfblockread(self.fid, LINK, 1) for Link in range(temps['link_count'] - 1)]
# data section
temps['dl_flags'] = temps.mdfblockread(self.fid, UINT8, 1)
temps['dl_reserved'] = temps.mdfblockreadBYTE(self.fid, 3)
temps['dl_count'] = temps.mdfblockread(self.fid, UINT32, 1)
if temps['dl_flags']: # equal length datalist
temps['dl_equal_length'] = temps.mdfblockread(self.fid, UINT64, 1)
else: # datalist defined by byte offset
temps['dl_offset'] = temps.mdfblockread(self.fid, UINT64, temps['dl_count'])
if temps['dl_dl_next']:
index = 1
while temps['dl_dl_next']: # reads pointers to all data blocks (DT, RD, SD, DZ)
temp = MDFBlock()
temp.loadHeader(self.fid, temps['dl_dl_next'])
temps['dl_dl_next'] = temp.mdfblockread(self.fid, LINK, 1)
temps['dl_data'][index] = [temp.mdfblockread(self.fid, LINK, 1) for Link in range(temp['link_count'] - 1)]
index += 1
if temps['dl_count']:
# read and concatenate raw blocks
buf = bytearray()
for DL in temps['dl_data']:
for pointer in temps['dl_data'][DL]:
# read fist data blocks linked by DLBlock to identify data block type
data_block = MDFBlock()
data_block.loadHeader(self.fid, pointer)
if data_block['id'] in ('##DT', '##RD', b'##DT', b'##RD', '##SD', b'##SD'):
buf.extend(self.fid.read(data_block['length'] - 24))
elif data_block['id'] in ('##DZ', b'##DZ'):
data_block['dz_org_block_type'] = data_block.mdfblockreadCHAR(self.fid, 2)
data_block['dz_zip_type'] = data_block.mdfblockread(self.fid, UINT8, 1)
data_block['dz_reserved'] = data_block.mdfblockreadBYTE(self.fid, 1)
data_block['dz_zip_parameter'] = data_block.mdfblockread(self.fid, UINT32, 1)
data_block['dz_org_data_length'] = data_block.mdfblockread(self.fid, UINT64, 1)
data_block['dz_data_length'] = data_block.mdfblockread(self.fid, UINT64, 1)
data_block['data'] = decompress_datablock(self.fid.read(data_block['dz_data_length']),
data_block['dz_zip_type'],
data_block['dz_zip_parameter'], data_block['dz_org_data_length'])
buf.extend(data_block['data'])
data_block['id'] = '##DT' # do not uncompress in DATABlock function
data_block['data'] = buf
temps['data'] = DATABlock(record, parent_block=data_block, channelList=nameList, sortedFlag=sortedFlag)
else: # empty datalist
temps['data'] = None
elif temps['id'] in ('##HL', b'##HL'): # header list block for DZBlock
# link section
temps['hl_dl_first'] = temps.mdfblockread(self.fid, LINK, 1)
# data section
temps['hl_flags'] = temps.mdfblockread(self.fid, UINT16, 1)
temps['hl_zip_type'] = temps.mdfblockread(self.fid, UINT8, 1)
temps['hl_reserved'] = temps.mdfblockreadBYTE(self.fid, 5)
self.pointerTodata = temps['hl_dl_first']
temps['data'] = self.load(record, zip=temps['hl_zip_type'], nameList=nameList, sortedFlag=sortedFlag)
elif temps['id'] in ('##DT', '##RD', b'##DT', b'##RD'): # normal sorted data block, direct read
temps['data'] = record.readSortedRecord(self.fid, self.pointerTodata, channelList=nameList)
elif temps['id'] in ('##SD', b'##SD'): # VLSD
temps['data'] = self.fid.read(temps['length'] - 24)
temps['data'] = DATABlock(record, parent_block=temps, channelList=nameList, sortedFlag=sortedFlag)
elif temps['id'] in ('##DZ', b'##DZ'): # zipped data block
temps['dz_org_block_type'] = temps.mdfblockreadCHAR(self.fid, 2)
temps['dz_zip_type'] = temps.mdfblockread(self.fid, UINT8, 1)
temps['dz_reserved'] = temps.mdfblockreadBYTE(self.fid, 1)
temps['dz_zip_parameter'] = temps.mdfblockread(self.fid, UINT32, 1)
temps['dz_org_data_length'] = temps.mdfblockread(self.fid, UINT64, 1)
temps['dz_data_length'] = temps.mdfblockread(self.fid, UINT64, 1)
temps['data'] = self.fid.read(temps['dz_data_length'])
temps['data'] = DATABlock(record, parent_block=temps, channelList=nameList, sortedFlag=sortedFlag)
else:
raise Exception('unknown data block')
return temps['data']
def readRecord(self, recordID, buf, channelList=None):
""" read record from a buffer
Parameters
----------------
recordID : int
record identifier
buf : str
buffer of data from file to be converted to channel raw data
channelList : list of str
list of channel names to be read
"""
return self[recordID]['record'].readRecordBuf(buf, channelList)
class channel():
""" channel class gathers all about channel structure in a record
Attributes
--------------
name : str
Name of channel
unit : str, default empty string
channel unit
desc : str
channel description
type : str
channel type. Can be 'standard', 'CANOpen' or 'InvalidBytes'
conversion : info class
conversion dictionnary
channelNumber : int
channel number corresponding to mdfinfo3.info3 class
channelGroup : int
channel group number corresponding to mdfinfo3.info3 class
dataGroup : int
data group number corresponding to mdfinfo3.info3 class
signalDataType : int
signal type according to specification
bitCount : int
number of bits used to store channel record
nBytes : int
number of bytes (1 byte = 8 bits) taken by channel record
dataFormat : str
numpy dtype as string
Format :
C format understood by fread
CFormat : struct class instance
struct instance to convert from C Format
byteOffset : int
position of channel record in complete record in bytes
bitOffset : int
bit position of channel value inside byte in case of channel having bit count below 8
RecordFormat : list of str
dtype format used for numpy.core.records functions ((name,name_title),str_stype)
channelType : int
channel type ; 0 fixed length data, 1 VLSD, 2 master, 3 virtual master,
4 sync, 5 MLSD, 6 virtual data
channelSyncType : int
channel synchronisation type ; 0 None, 1 Time, 2 Angle, 3 Distance, 4 Index
posByteBeg : int
start position in number of byte of channel record in complete record
posByteEnd : int
end position in number of byte of channel record in complete record
posBitBeg : int
start position in number of bit of channel record in complete record
posBitEnd : int
end position in number of bit of channel record in complete record
VLSD_CG_Flag : bool
flag when Channel Group VLSD is used
data : int
pointer to data block linked to a channel (VLSD, MLSD)
Methods
------------
__init__()
constructor
__str__()
to print class attributes
attachment(fid, info)
in case of sync channel attached
set(info, dataGroup, channelGroup, channelNumber, recordIDsize)
standard channel initialisation
setCANOpen(info, dataGroup, channelGroup, channelNumber, recordIDsize, name)
CANOpen channel initialisation
setInvalidBytes(info, dataGroup, channelGroup, recordIDsize, byte_aligned)
Invalid Bytes channel initialisation
"""
def __init__(self):
""" channel class constructor
"""
self.name = ''
type = 'standard'
self.channelNumber = 0
self.dataGroup = 0
self.channelGroup = 0
self.signalDataType = 0
self.channelSyncType = 0
self.bitCount = 0
self.nBytes = 0
self.little_endian = True
self.dataFormat = ''
self.CABlock = 0
self.channelType = 0
self.data = 0
self.maxLengthVLSDRecord = 0
self.RecordFormat = (('', ''), '')
self.Format = ''
self.bitOffset = 0
self.byteOffset = 0
self.posByteBeg = 0
self.posByteEnd = 0
self.posBitBeg = 0
self.posBitEnd = 0
self.VLSD_CG_Flag = False
self.unit = ''
self.desc = ''
self.conversion = None
def __str__(self):
output = str(self.channelNumber) + ' '
output += str(self.RecordFormat) + ' '
output += str(self.Format) + ' '
output += 'ChannelType ' + str(self.channelType) + ' '
output += 'DataType ' + str(self.signalDataType) + ' '
output += 'bitOffset ' + str(self.bitOffset) + ' '
output += 'ByteBeg ' + str(self.posByteBeg) + ' '
output += 'ByteEnd ' + str(self.posByteEnd) + ' '
output += 'BitBeg ' + str(self.posBitBeg) + ' '
output += 'BitEnd ' + str(self.posBitEnd)
output += 'unit ' + self.unit
output += 'description ' + self.desc
return output
def attachment(self, fid, info): # in case of sync channel attached to channel
return ATBlock(fid, info['CNBlock'][self.dataGroup][self.channelGroup][self.channelNumber]['cn_data'])
def set(self, info, dataGroup, channelGroup, channelNumber, recordIDsize):
""" standard record channel initialisation
Parameters
------------
info : mdfinfo4.info4 class
dataGroup : int
data group number in mdfinfo4.info4 class
channelGroup : int
channel group number in mdfinfo4.info4 class
channelNumber : int
channel number in mdfinfo4.info4 class
recordIDsize : int
size of record ID in Bytes
"""
self.type = 'standard'
self.name = info['CNBlock'][dataGroup][channelGroup][channelNumber]['name']
self.channelNumber = channelNumber
self.dataGroup = dataGroup
self.channelGroup = channelGroup
self.signalDataType = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_data_type']
self.channelSyncType = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_sync_type']
self.bitCount = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_bit_count']
self.nBytes = bits_to_bytes(self.bitCount)
if self.signalDataType in (1, 3, 5, 9): # endianness
self.little_endian = False
else:
self.little_endian = True
if info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_composition'] and \
'CABlock' in info['CNBlock'][dataGroup][channelGroup][channelNumber]: # channel array
self.dataFormat = arrayformat4(self.signalDataType, self.bitCount)
self.CABlock = info['CNBlock'][dataGroup][channelGroup][channelNumber]['CABlock']
self.nBytes *= self.CABlock['PNd'] # calculates total array size in bytes
if self.CABlock['ca_ndim'] > 1:
array_desc = str(tuple(self.CABlock['ca_dim_size']))
else:
array_desc = str(self.CABlock['ca_dim_size'])
self.dataFormat = array_desc + self.dataFormat
else: # not channel array
self.dataFormat = arrayformat4(self.signalDataType, self.bitCount)
self.channelType = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_type']
if self.channelType in (1, 4, 5): # if VSLD or sync or max length channel
self.data = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_data']
if self.channelType == 1: # if VSLD
self.dataFormat = arrayformat4(0, self.bitCount)
self.maxLengthVLSDRecord = 0 # initialises max length of SDBlock elements to 0 for later calculation
if self.channelType in (2, 3): # master channel, add datagroup number to avoid overwriting same sames like time
self.name += str(dataGroup)
self.RecordFormat = ((self.name, convertName(self.name)), self.dataFormat)
if self.signalDataType not in (13, 14): # processed by several channels
if not self.channelType == 1: # if not VSLD
self.Format = datatypeformat4(self.signalDataType, self.bitCount)
else: # VLSD
self.Format = datatypeformat4(0, self.bitCount)
self.CFormat = Struct(self.Format)
self.bitOffset = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_bit_offset']
self.byteOffset = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_byte_offset']
self.posByteBeg = recordIDsize + self.byteOffset
self.posByteEnd = self.posByteBeg + self.nBytes
self.posBitBeg = self.posByteBeg * 8 + self.bitOffset
self.posBitEnd = self.posBitBeg + self.bitCount
self.VLSD_CG_Flag = False
if 'unit' in list(info['CCBlock'][dataGroup][channelGroup][channelNumber].keys()):
self.unit = info['CCBlock'][dataGroup][channelGroup][channelNumber]['unit']
elif 'unit' in list(info['CNBlock'][dataGroup][channelGroup][channelNumber].keys()):
self.unit = info['CNBlock'][dataGroup][channelGroup][channelNumber]['unit']
else:
self.unit = ''
if 'Comment' in self.unit:
self.unit = self.unit['Comment']
if 'Comment' in list(info['CNBlock'][dataGroup][channelGroup][channelNumber].keys()):
self.desc = info['CNBlock'][dataGroup][channelGroup][channelNumber]['Comment']
if self.desc is not None and 'description' in self.desc:
self.desc = self.desc['description']
if self.desc is not None and 'name' in self.desc:
self.desc = self.desc['name']
else:
self.desc = ''
self.conversion = info['CCBlock'][dataGroup][channelGroup][channelNumber]
def setCANOpen(self, info, dataGroup, channelGroup, channelNumber, recordIDsize, name):
""" CANOpen channel intialisation
Parameters
------------
info : mdfinfo4.info4 class
dataGroup : int
data group number in mdfinfo4.info4 class
channelGroup : int
channel group number in mdfinfo4.info4 class
channelNumber : int
channel number in mdfinfo4.info4 class
recordIDsize : int
size of record ID in Bytes
name : str
name of channel. Should be in ('ms', 'day', 'days', 'hour', 'month', 'min', 'year')
"""
self.type = 'CANOpen'
self.name = name
self.unit = name
self.channelNumber = channelNumber
self.dataGroup = dataGroup
self.channelGroup = channelGroup
self.signalDataType = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_data_type']
self.channelSyncType = 0
if self.name == 'ms':
offset = 0
self.desc = 'ms'
if self.signalDataType == 13:
self.bitCount = 16
self.dataFormat = '<u2'
else:
self.bitCount = 32
self.dataFormat = '<u4'
elif self.name == 'days':
self.bitCount = 16
self.dataFormat = '<u2'
offset = 4
self.desc = 'days'
else:
self.bitCount = 8
self.dataFormat = '<u1'
if self.name == 'min':
offset = 2
self.desc = 'min'
elif self.name == 'hour':
offset = 3
self.desc = 'hour'
elif self.name == 'day':
offset = 4
self.desc = 'day'
elif self.name == 'month':
offset = 5
self.desc = 'month'
elif self.name == 'year':
offset = 6
self.desc = 'year'
else:
raise('CANopen type not understood')
self.nBytes = bits_to_bytes(self.bitCount)
self.little_endian = True
self.channelType = 0
self.maxLengthVLSDRecord = 0 # initialises max length of SDBlock elements to 0 for later calculation
self.RecordFormat = ((self.name, convertName(self.name)), self.dataFormat)
self.bitOffset = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_bit_offset'] + offset*8
self.byteOffset = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_byte_offset'] + offset
self.posByteBeg = recordIDsize + self.byteOffset
self.posByteEnd = self.posByteBeg + self.nBytes
self.posBitBeg = self.posByteBeg * 8 + self.bitOffset
self.posBitEnd = self.posBitBeg + self.bitCount
self.signalDataType = 0
def setInvalidBytes(self, info, dataGroup, channelGroup, recordIDsize, byte_aligned=True):
""" invalid_bytes channel initialisation
Parameters
----------
info : mdfinfo4.info4 class
dataGroup : int
data group number in mdfinfo4.info4 class
channelGroup : int
channel group number in mdfinfo4.info4 class
channelNumber : int
channel number in mdfinfo4.info4 class
recordIDsize : int
size of record ID in Bytes
byte_aligned : Bool
Flag for byte alignement
"""
self.type = 'InvalidBytes'
self.name = u'invalid_bytes' + str(dataGroup)
self.unit = ''
self.desc = ''
self.conversion = ''
if byte_aligned:
self.signalDataType = 10 # byte array
else:
self.signalDataType = 0 # uint LE
self.little_endian = True # default to little endian
self.nBytes = info['CGBlock'][dataGroup][channelGroup]['cg_invalid_bytes']
self.bitCount = self.nBytes * 8
self.channelType = 0 # fixed length data
self.dataFormat = str(self.nBytes) + 'V'
self.RecordFormat = ((self.name, convertName(self.name)), self.dataFormat)
self.Format = str(self.nBytes) + 's'
self.CFormat = Struct(self.Format)
self.bitOffset = 0
self.byteOffset = info['CGBlock'][dataGroup][channelGroup]['cg_data_bytes']
self.posByteBeg = recordIDsize + self.byteOffset
self.posByteEnd = self.posByteBeg + self.nBytes
self.posBitBeg = self.posByteBeg * 8 + self.bitOffset
self.posBitEnd = self.posBitBeg + self.bitCount
self.VLSD_CG_Flag = False
self.invalid_bit = {}
for channelNumber in info['CNBlock'][dataGroup][channelGroup]:
name = info['CNBlock'][dataGroup][channelGroup][channelNumber]['name']
self.invalid_bit[name] = info['CNBlock'][dataGroup][channelGroup][channelNumber]['cn_invalid_bit_pos']
self.invalid_bytes = None
def validity_channel(self, channelName):
""" extract channel validity bits
Parameters
----------
channelName : str
channel name
Return
-------
Numpy vector of validity
"""
if self.type == 'InvalidBytes':
return bitwise_and(right_shift(self.invalid_bytes, self.invalid_bit[channelName]), 1)
else:
raise('asking for invalid byte array but channel is not invalid byte type')
class record(list):
""" record class listing channel classes. It is representing a channel group
Attributes
--------------
CGrecordLength : int
length of record corresponding of channel group in Byte CG Block information
recordLength : int
length of record as understood by program based on C datatypes
numberOfRecords : int
number of records in data block
recordID : int
recordID corresponding to channel group
recordIDsize : int
size of recordID
recordIDCFormat : str
record identifier C format string as understood by fread
dataGroup : int:
data group number
channelGroup : int
channel group number
numpyDataRecordFormat : list
list of numpy (dtype) for each channel
dataRecordName : list
list of channel names used for recarray attribute definition
master : dict
define name and number of master channel
recordToChannelMatching : dict
helps to identify nested bits in byte
channelNames : list
channel names to be stored, useful for low memory consumption but slow
Flags : bool
channel flags as from specification
VLSD_CG : dict
dict of Channel Group VLSD, key being recordID
VLSD : list of channel classes
list of channel classes being VLSD
MLSD : dict
copy from info['MLSD'] if existing
byte_aligned : Bool, True by default
flag for byte aligned record
hiddenBytes : Bool, False by default
flag in case of non declared channels in record, forces to use readBitarray
invalid_channel : Default None
invalid_byte class if existing in record otherwise None
CANOpen : str, Default None
'time' if record contains CANOpen time channel, same for 'date'
Methods
------------
addChannel(info, channelNumber)
loadInfo(info)
readSortedRecord(fid, pointer, channelList=None)
readRecordBuf(buf, channelList=None)
readBitarray(bita, channelList=None)
"""
def __init__(self, dataGroup, channelGroup):
self.CGrecordLength = 0
self.recordLength = 0
self.numberOfRecords = 0
self.recordID = 0
self.recordIDsize = 0
self.recordIDCFormat = ''
self.dataGroup = dataGroup
self.channelGroup = channelGroup
self.numpyDataRecordFormat = []
self.dataRecordName = []
self.master = {}
self.master['name'] = 'master_' + str(dataGroup)
self.master['number'] = None
self.Flags = 0
self.VLSD_CG = {}
self.VLSD = []
self.MLSD = {}
self.recordToChannelMatching = {}
self.channelNames = []
self.byte_aligned = True
self.hiddenBytes = False
self.invalid_channel = None
self.CANOpen = None
def __str__(self):
output = 'Channels : ' + str(len(self)) + '\n'
for chan in self:
output += chan.name + '\n'
output += str(chan.channelNumber) + ' '
output += str(chan.RecordFormat) + ' '
output += str(chan.Format) + ' '
output += 'ChannelType ' + str(chan.channelType) + ' '
output += 'DataType ' + str(chan.signalDataType) + '\n'
output += 'Datagroup number : ' + str(self.dataGroup) + '\n'
output += 'Byte aligned : ' + str(self.byte_aligned) + '\n'
if self.master['name'] is not None:
output += 'Master channel : ' + self.master['name'] + '\n'
output += 'Numpy records format : \n'
for record in self.numpyDataRecordFormat:
output += str(record) + '\n'
output += 'VLSD_CG' + str(self.VLSD_CG)
return output
def addChannel(self, info, channelNumber):
""" add a channel in class
Parameters
----------------
info : mdfinfo4.info4 class
channelNumber : int
channel number in mdfinfo4.info4 class
"""
Channel = channel()
self.append(Channel.set(info, self.dataGroup, self.channelGroup, channelNumber, self.recordIDsize))
self.channelNames.append(self[-1].name)
def loadInfo(self, info):
""" gathers records related from info class
Parameters
----------------
info : mdfinfo4.info4 class
"""
self.CGrecordLength = info['CGBlock'][self.dataGroup][self.channelGroup]['cg_data_bytes']
self.recordIDsize = info['DGBlock'][self.dataGroup]['dg_rec_id_size']
if not self.recordIDsize == 0: # no record ID
self.dataRecordName.append('RecordID' + str(self.channelGroup))
format = (self.dataRecordName[-1], convertName(self.dataRecordName[-1]))
if self.recordIDsize == 1:
self.numpyDataRecordFormat.append((format, 'uint8'))
self.recordIDCFormat = Struct('B')
self.recordLength += 1
self.CGrecordLength += 1
elif self.recordIDsize == 2:
self.numpyDataRecordFormat.append((format, 'uint16'))
self.recordIDCFormat = 'H'
self.recordLength += 2
self.CGrecordLength += 2
elif self.recordIDsize == 3:
self.numpyDataRecordFormat.append((format, 'uint32'))
self.recordIDCFormat = 'I'
self.recordLength += 3
self.CGrecordLength += 3
elif self.recordIDsize == 4:
self.numpyDataRecordFormat.append((format, 'uint64'))
self.recordIDCFormat = 'L'
self.recordLength += 4
self.CGrecordLength += 4
self.recordID = info['CGBlock'][self.dataGroup][self.channelGroup]['cg_record_id']
self.numberOfRecords = info['CGBlock'][self.dataGroup][self.channelGroup]['cg_cycle_count']
self.Flags = info['CGBlock'][self.dataGroup][self.channelGroup]['cg_flags']
if 'MLSD' in info:
self.MLSD = info['MLSD']
for channelNumber in list(info['CNBlock'][self.dataGroup][self.channelGroup].keys()):
Channel = channel()
Channel.set(info, self.dataGroup, self.channelGroup, channelNumber, self.recordIDsize)
if Channel.channelType in (2, 3): # master channel found
if self.master['number'] is None or Channel.channelSyncType==1: # new master channel found
# or more than 1 master channel, priority to time channel
self.master['number'] = channelNumber
self.master['name'] = Channel.name
if Channel.channelType in (0, 1, 2, 4, 5): # not virtual channel
if Channel.signalDataType == 13:
for name in ('ms', 'min', 'hour', 'day', 'month', 'year'):
Channel = channel() # new object otherwise only modified
Channel.setCANOpen(info, self.dataGroup, self.channelGroup, channelNumber, self.recordIDsize, name)
self.append(Channel)