Debian Codegraph @

test/test_mdf.py

raw
1 #!/usr/bin/env python
2 from io import BytesIO
3 import os
4 from pathlib import Path
5 import random
6 import sys
7 import tempfile
8 import unittest
9 import urllib
10 import urllib.request
11 from zipfile import ZipFile
12
13 import numexpr
14 import numpy as np
15 import numpy.typing as npt
16 from pandas import DataFrame
17 from typing_extensions import Any
18
19 from asammdf import MDF, Signal, SUPPORTED_VERSIONS
20 from asammdf.blocks.utils import MdfException
21 from asammdf.mdf import SearchMode
22
23 from .utils import cycles, generate_arrays_test_file, generate_test_file
24
25 SUPPORTED_VERSIONS = tuple(version for version in SUPPORTED_VERSIONS if "4.20" > version >= "3.20") # type: ignore[misc]
26
27 CHANNEL_LEN = 100000
28
29
30 @unittest.skipIf(os.getenv("NO_NET_ACCESS"), "Test requires Internet access")
31 class TestMDF(unittest.TestCase):
32 tempdir_demo: tempfile.TemporaryDirectory[str]
33 tempdir_array: tempfile.TemporaryDirectory[str]
34 tempdir_general: tempfile.TemporaryDirectory[str]
35 tempdir: tempfile.TemporaryDirectory[str]
36
37 def test_measurement(self) -> None:
38 self.assertTrue(MDF)
39
40 @classmethod
41 def setUpClass(cls) -> None:
42 url = "https://github.com/danielhrisca/asammdf/files/4078993/test.demo.zip"
43 urllib.request.urlretrieve(url, "test.zip")
44
45 cls.tempdir_demo = tempfile.TemporaryDirectory()
46 cls.tempdir_general = tempfile.TemporaryDirectory()
47 cls.tempdir = tempfile.TemporaryDirectory()
48 cls.tempdir_array = tempfile.TemporaryDirectory()
49
50 ZipFile(r"test.zip").extractall(cls.tempdir_demo.name)
51 Path("test.zip").unlink()
52 for version in ("3.30", "4.10"):
53 generate_test_file(cls.tempdir_general.name, version)
54
55 generate_arrays_test_file(cls.tempdir_array.name)
56
57 def test_mdf_header(self) -> None:
58 mdf = BytesIO(b"M" * 100)
59 with self.assertRaises(MdfException):
60 MDF(mdf)
61
62 mdf.close()
63
64 def test_wrong_header_version(self) -> None:
65 mdf = BytesIO(
66 b"MDF AAAA amdf500d\x00\x00\x00\x00\x9f\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
67 )
68 with self.assertRaises(MdfException):
69 MDF(mdf)
70
71 mdf.close()
72
73 def test_read(self) -> None:
74 print("MDF read big files")
75 for input_file in Path(TestMDF.tempdir_general.name).iterdir():
76 print(input_file)
77
78 equal = True
79
80 for inp in (input_file, BytesIO(input_file.read_bytes())):
81 with MDF(inp) as mdf:
82 for i, group in enumerate(mdf.groups):
83 v: npt.NDArray[Any]
84 if i == 0:
85 v = np.ones(cycles, dtype=np.uint64)
86 for j in range(1, 20):
87 vals = mdf.get(group=i, index=j, samples_only=True)[0]
88 if not np.array_equal(vals, v * (j - 1)):
89 equal = False
90 elif i == 1:
91 v = np.ones(cycles, dtype=np.int64)
92 for j in range(1, 20):
93 vals = mdf.get(group=i, index=j, samples_only=True)[0]
94 if not np.array_equal(vals, v * (j - 1) - 0.5):
95 equal = False
96 elif i == 2:
97 v = np.arange(cycles, dtype=np.int64) / 100.0
98 form = "{} * sin(v)"
99 for j in range(1, 20):
100 vals = mdf.get(group=i, index=j, samples_only=True)[0]
101 f = form.format(j - 1)
102 if not np.array_equal(vals, numexpr.evaluate(f)):
103 equal = False
104 elif i == 3:
105 v = np.ones(cycles, dtype=np.int64)
106 form = "({} * v -0.5) / 1"
107 for j in range(1, 20):
108 f = form.format(j - 1)
109 vals = mdf.get(group=i, index=j, samples_only=True)[0]
110 if not np.array_equal(vals, numexpr.evaluate(f)):
111 equal = False
112 elif i == 4:
113 for j in range(1, 20):
114 target = np.array([f"Channel {j} sample {k}".encode("ascii") for k in range(cycles)])
115 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
116 cond = np.array_equal(vals, target)
117 if not cond:
118 print(i, j, vals, target, len(vals), len(target))
119 self.assertTrue(cond)
120
121 elif i == 5:
122 v = np.ones(cycles, dtype=np.dtype("(8,)u1"))
123 for j in range(1, 20):
124 target = v * j
125 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
126 cond = np.array_equal(vals, target)
127 if not cond:
128 print(i, j, vals, target, len(vals), len(target))
129 self.assertTrue(cond)
130
131 elif i == 6:
132 for j in range(1, 20):
133 target = np.array([b"Value %d" % j for _ in range(cycles)])
134 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
135 cond = np.array_equal(vals, target)
136 if not cond:
137 print(i, j, vals, target, len(vals), len(target))
138 self.assertTrue(cond)
139
140 if isinstance(inp, BytesIO):
141 inp.close()
142 self.assertTrue(equal)
143
144 def test_read_arrays(self) -> None:
145 print("MDF read big array files")
146 for input_file in Path(TestMDF.tempdir_array.name).iterdir():
147 print(input_file)
148
149 equal = True
150
151 for inp in (input_file, BytesIO(input_file.read_bytes())):
152 with MDF(inp) as mdf:
153 mdf.configure(read_fragment_size=8000)
154
155 for i, group in enumerate(mdf.groups):
156 if i == 0:
157 samples_list = [
158 np.ones((cycles, 2, 3), dtype=np.uint64),
159 np.ones((cycles, 2), dtype=np.uint64),
160 np.ones((cycles, 3), dtype=np.uint64),
161 ]
162
163 for j in range(1, 20):
164 types: list[npt.DTypeLike] = [
165 (f"Channel_{j}", "(2, 3)<u8"),
166 (f"channel_{j}_Y_axis", "(2, )<u8"),
167 (f"channel_{j}_X_axis", "(3, )<u8"),
168 ]
169 dtype = np.dtype(types)
170
171 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
172 arrays = [arr * j for arr in samples_list]
173 target = np.rec.fromarrays(arrays, dtype=dtype)
174 if not np.array_equal(vals, target):
175 equal = False
176 raise Exception
177
178 elif i == 1:
179 samples = np.ones((cycles, 2, 3), dtype=np.uint64)
180 axis_0 = np.ones((cycles, 2), dtype=np.uint64)
181 axis_1 = np.ones((cycles, 3), dtype=np.uint64)
182
183 for j in range(1, 20):
184 types = [(f"Channel_{j}", "(2, 3)<u8")]
185 dtype = np.dtype(types)
186
187 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
188 arrays = [samples * j]
189 target = np.rec.fromarrays(arrays, dtype=dtype)
190 if not np.array_equal(vals, target):
191 equal = False
192 raise Exception
193
194 elif i == 2:
195 samples_list = [
196 np.ones(cycles, dtype=np.uint8),
197 np.ones(cycles, dtype=np.uint16),
198 np.ones(cycles, dtype=np.uint32),
199 np.ones(cycles, dtype=np.uint64),
200 np.ones(cycles, dtype=np.int8),
201 np.ones(cycles, dtype=np.int16),
202 np.ones(cycles, dtype=np.int32),
203 np.ones(cycles, dtype=np.int64),
204 ]
205
206 for j in range(1, 20):
207 types = [
208 (f"struct_{j}_channel_0", np.uint8),
209 (f"struct_{j}_channel_1", np.uint16),
210 (f"struct_{j}_channel_2", np.uint32),
211 (f"struct_{j}_channel_3", np.uint64),
212 (f"struct_{j}_channel_4", np.int8),
213 (f"struct_{j}_channel_5", np.int16),
214 (f"struct_{j}_channel_6", np.int32),
215 (f"struct_{j}_channel_7", np.int64),
216 ]
217 dtype = np.dtype(types)
218
219 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
220 arrays = [arr * j for arr in samples_list]
221 target = np.rec.fromarrays(arrays, dtype=dtype)
222 if not np.array_equal(vals, target):
223 equal = False
224 print(target)
225 print(vals)
226 raise Exception
227
228 if isinstance(inp, BytesIO):
229 inp.close()
230
231 self.assertTrue(equal)
232
233 def test_read_demo(self) -> None:
234 print("MDF read tests")
235
236 mdf_files = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix in (".mdf", ".mf4")]
237
238 signals = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix == ".npy"]
239
240 for file in mdf_files:
241 print(file)
242
243 for inp in (file, BytesIO(file.read_bytes())):
244 with MDF(inp, use_display_names=True) as input_file:
245 for signal in signals:
246 name = signal.stem
247 target = np.load(signal)
248 values = input_file.get(name, *input_file.whereis(name)[0]).samples
249
250 self.assertTrue(np.array_equal(target, values))
251
252 if isinstance(inp, BytesIO):
253 inp.close()
254
255 def test_convert(self) -> None:
256 print("MDF convert big files tests")
257
258 for out in SUPPORTED_VERSIONS:
259 for input_file in Path(TestMDF.tempdir_general.name).iterdir():
260 for compression in (0, 1, 2):
261 print(input_file, out, compression)
262
263 with MDF(input_file) as mdf:
264 mdf.configure(read_fragment_size=8000)
265 converted = mdf.convert(out)
266 outfile = converted.save(
267 Path(TestMDF.tempdir.name) / f"tmp_convert_{out}",
268 overwrite=True,
269 compression=compression,
270 )
271 converted.close()
272
273 equal = True
274
275 with MDF(outfile) as mdf:
276 mdf.configure(read_fragment_size=8000)
277
278 for i, group in enumerate(mdf.groups):
279 v: npt.NDArray[Any]
280 if i == 0:
281 v = np.ones(cycles, dtype=np.uint64)
282 for j in range(1, 20):
283 vals = mdf.get(group=i, index=j, samples_only=True)[0]
284 if not np.array_equal(vals, v * (j - 1)):
285 equal = False
286 print(outfile)
287 print(vals, len(vals))
288 print(v * (j - 1), len(v))
289
290 raise Exception
291 elif i == 1:
292 v = np.ones(cycles, dtype=np.int64)
293 for j in range(1, 20):
294 vals = mdf.get(group=i, index=j, samples_only=True)[0]
295 if not np.array_equal(vals, v * (j - 1) - 0.5):
296 equal = False
297 raise Exception
298 elif i == 2:
299 v = np.arange(cycles, dtype=np.int64) / 100.0
300 form = "{} * sin(v)"
301 for j in range(1, 20):
302 vals = mdf.get(group=i, index=j, samples_only=True)[0]
303 f = form.format(j - 1)
304 if not np.array_equal(vals, numexpr.evaluate(f)):
305 equal = False
306 raise Exception
307 elif i == 3:
308 v = np.ones(cycles, dtype=np.int64)
309 form = "({} * v -0.5) / 1"
310 for j in range(1, 20):
311 f = form.format(j - 1)
312 vals = mdf.get(group=i, index=j, samples_only=True)[0]
313 if not np.array_equal(vals, numexpr.evaluate(f)):
314 equal = False
315 target = numexpr.evaluate(f)
316 print(i, j, vals, target, len(vals), len(target))
317 raise Exception
318 elif i == 4:
319 for j in range(1, 20):
320 target = np.array(
321 [f"Channel {j} sample {k}".encode("ascii") for k in range(cycles)]
322 )
323 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
324 cond = np.array_equal(vals, target)
325 if not cond:
326 print(i, j, vals, target, len(vals), len(target))
327 raise Exception
328 self.assertTrue(cond)
329
330 elif i == 5:
331 v = np.ones(cycles, dtype=np.dtype("(8,)u1"))
332 for j in range(1, 20):
333 target = v * j
334 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
335 cond = np.array_equal(vals, target)
336 if not cond:
337 print(i, j, vals, target, len(vals), len(target))
338 raise Exception
339 self.assertTrue(cond)
340
341 elif i == 6:
342 for j in range(1, 20):
343 target = np.array([b"Value %d" % j for _ in range(cycles)])
344 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
345 cond = np.array_equal(vals, target)
346 if not cond:
347 print(i, j, vals, target, len(vals), len(target))
348 raise Exception
349 self.assertTrue(cond)
350
351 self.assertTrue(equal)
352
353 def test_convert_demo(self) -> None:
354 print("MDF convert demo tests")
355
356 mdf_files = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix in (".mdf", ".mf4")]
357
358 signals = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix == ".npy"]
359
360 for file in mdf_files:
361 for inp in (file, BytesIO(file.read_bytes())):
362 with MDF(inp, use_display_names=True) as input_file:
363 for out in SUPPORTED_VERSIONS:
364 print(file, out, type(inp))
365
366 converted = input_file.convert(out)
367 outfile = converted.save(Path(TestMDF.tempdir_demo.name) / "tmp", overwrite=True)
368 converted.close()
369
370 with MDF(outfile, use_display_names=True) as mdf:
371 for signal in signals:
372 name = signal.stem
373 target = np.load(signal)
374 values = mdf.get(name, *mdf.whereis(name)[0]).samples
375
376 self.assertTrue(np.array_equal(target, values))
377
378 if isinstance(inp, BytesIO):
379 inp.close()
380
381 def test_cut(self) -> None:
382 print("MDF cut big files tests")
383
384 for input_file in Path(TestMDF.tempdir_general.name).iterdir():
385 for whence in (0, 1):
386 for compression in (0, 1, 2):
387 mdf = MDF(input_file)
388
389 mdf.configure(read_fragment_size=8000)
390 cut = mdf.cut(stop=-1, whence=whence, include_ends=False)
391 outfile0 = cut.save(Path(TestMDF.tempdir.name) / "tmp0", overwrite=True)
392 cut.close()
393
394 mdf.configure(read_fragment_size=8000)
395 cut = mdf.cut(stop=105, whence=whence, include_ends=False)
396 outfile1 = cut.save(Path(TestMDF.tempdir.name) / "tmp1", overwrite=True)
397 cut.close()
398
399 mdf.configure(read_fragment_size=8000)
400 cut = mdf.cut(start=105.1, stop=201, whence=whence, include_ends=False)
401 outfile2 = cut.save(Path(TestMDF.tempdir.name) / "tmp2", overwrite=True)
402 cut.close()
403
404 mdf.configure(read_fragment_size=8000)
405 cut = mdf.cut(start=201.1, whence=whence, include_ends=False)
406 outfile3 = cut.save(Path(TestMDF.tempdir.name) / "tmp3", overwrite=True)
407 cut.close()
408
409 mdf.configure(read_fragment_size=8000)
410 cut = mdf.cut(start=7000, whence=whence, include_ends=False)
411 outfile4 = cut.save(Path(TestMDF.tempdir.name) / "tmp4", overwrite=True)
412 cut.close()
413
414 concatenated = MDF.concatenate(
415 [outfile0, outfile1, outfile2, outfile3, outfile4],
416 version=mdf.version,
417 sync=bool(whence),
418 )
419
420 outfile = concatenated.save(
421 Path(TestMDF.tempdir.name) / "tmp_cut",
422 overwrite=True,
423 compression=compression,
424 )
425
426 mdf.close()
427 concatenated.close()
428
429 with MDF(outfile) as mdf:
430 for i, group in enumerate(mdf.groups):
431 v: npt.NDArray[Any]
432 if i == 0:
433 v = np.ones(cycles, dtype=np.uint64)
434 for j in range(1, 20):
435 vals = mdf.get(group=i, index=j, samples_only=True)[0]
436 cond = np.array_equal(vals, v * (j - 1))
437 if not cond:
438 print(i, j, vals, v * (j - 1), len(vals), len(v))
439 self.assertTrue(cond)
440 elif i == 1:
441 v = np.ones(cycles, dtype=np.int64)
442 for j in range(1, 20):
443 vals = mdf.get(group=i, index=j, samples_only=True)[0]
444 cond = np.array_equal(vals, v * (j - 1) - 0.5)
445 if not cond:
446 print(vals, v * (j - 1) - 0.5, len(vals), len(v))
447 self.assertTrue(cond)
448 elif i == 2:
449 v = np.arange(cycles, dtype=np.int64) / 100.0
450 form = "{} * sin(v)"
451 for j in range(1, 20):
452 vals = mdf.get(group=i, index=j, samples_only=True)[0]
453 f = form.format(j - 1)
454 target = numexpr.evaluate(f)
455 cond = np.array_equal(vals, target)
456 if not cond:
457 print(i, j, vals, target, len(vals), len(target))
458 self.assertTrue(cond)
459 elif i == 3:
460 v = np.ones(cycles, dtype=np.int64)
461 form = "({} * v -0.5) / 1"
462 for j in range(1, 20):
463 f = form.format(j - 1)
464 vals = mdf.get(group=i, index=j, samples_only=True)[0]
465 target = numexpr.evaluate(f)
466 cond = np.array_equal(vals, target)
467 if not cond:
468 print(i, j, vals, target, len(vals), len(target))
469 self.assertTrue(cond)
470 elif i == 4:
471 for j in range(1, 20):
472 target = np.array(
473 [f"Channel {j} sample {k}".encode("ascii") for k in range(cycles)]
474 )
475 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
476 cond = np.array_equal(vals, target)
477 if not cond:
478 print(i, j, vals, target, len(vals), len(target))
479 self.assertTrue(cond)
480
481 elif i == 5:
482 v = np.ones(cycles, dtype=np.dtype("(8,)u1"))
483 for j in range(1, 20):
484 target = v * j
485 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
486 cond = np.array_equal(vals, target)
487 if not cond:
488 print(i, j, vals, target, len(vals), len(target))
489 self.assertTrue(cond)
490
491 elif i == 6:
492 for j in range(1, 20):
493 target = np.array([b"Value %d" % j for _ in range(cycles)])
494 vals = mdf.get(group=i, index=j + 1, samples_only=True)[0]
495 cond = np.array_equal(vals, target)
496 if not cond:
497 print(i, j, vals, target, len(vals), len(target))
498 self.assertTrue(cond)
499
500 def test_cut_arrays(self) -> None:
501 print("MDF cut big array files")
502 for input_file in Path(TestMDF.tempdir_array.name).iterdir():
503 for whence in (0, 1):
504 print(input_file, whence)
505
506 mdf = MDF(input_file)
507
508 mdf.configure(read_fragment_size=8000)
509 cut = mdf.cut(stop=105.5, whence=whence, include_ends=False)
510 outfile1 = cut.save(Path(TestMDF.tempdir.name) / "tmp1", overwrite=True)
511 cut.close()
512
513 cut = mdf.cut(start=105.5, stop=201.5, whence=whence, include_ends=False)
514 outfile2 = cut.save(Path(TestMDF.tempdir.name) / "tmp2", overwrite=True)
515 cut.close()
516
517 cut = mdf.cut(start=201.5, whence=whence, include_ends=False)
518 outfile3 = cut.save(Path(TestMDF.tempdir.name) / "tmp3", overwrite=True)
519 cut.close()
520
521 concatenated = MDF.concatenate([outfile1, outfile2, outfile3], mdf.version)
522 outfile = concatenated.save(Path(TestMDF.tempdir.name) / "tmp_cut", overwrite=True)
523
524 mdf.close()
525 concatenated.close()
526
527 equal = True
528
529 with MDF(outfile) as mdf:
530 mdf.configure(read_fragment_size=8000)
531
532 for i, group in enumerate(mdf.groups):
533 if i == 0:
534 samples_list = [
535 np.ones((cycles, 2, 3), dtype=np.uint64),
536 np.ones((cycles, 2), dtype=np.uint64),
537 np.ones((cycles, 3), dtype=np.uint64),
538 ]
539
540 for j in range(1, 20):
541 types: list[npt.DTypeLike] = [
542 (f"Channel_{j}", "(2, 3)<u8"),
543 (f"channel_{j}_Y_axis", "(2, )<u8"),
544 (f"channel_{j}_X_axis", "(3, )<u8"),
545 ]
546 dtype = np.dtype(types)
547
548 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
549 arrays = [arr * j for arr in samples_list]
550 target = np.rec.fromarrays(arrays, dtype=dtype)
551 if not np.array_equal(vals, target):
552 equal = False
553 print(
554 i,
555 j,
556 len(target),
557 len(vals),
558 vals,
559 target,
560 sep="\n\n",
561 )
562 raise Exception
563
564 elif i == 1:
565 samples = np.ones((cycles, 2, 3), dtype=np.uint64)
566 axis_0 = np.ones((cycles, 2), dtype=np.uint64)
567 axis_1 = np.ones((cycles, 3), dtype=np.uint64)
568
569 for j in range(1, 20):
570 types = [(f"Channel_{j}", "(2, 3)<u8")]
571 dtype = np.dtype(types)
572
573 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
574 arrays = [samples * j]
575 target = np.rec.fromarrays(arrays, dtype=dtype)
576 if not np.array_equal(vals, target):
577 equal = False
578 raise Exception
579
580 elif i == 2:
581 samples_list = [
582 np.ones(cycles, dtype=np.uint8),
583 np.ones(cycles, dtype=np.uint16),
584 np.ones(cycles, dtype=np.uint32),
585 np.ones(cycles, dtype=np.uint64),
586 np.ones(cycles, dtype=np.int8),
587 np.ones(cycles, dtype=np.int16),
588 np.ones(cycles, dtype=np.int32),
589 np.ones(cycles, dtype=np.int64),
590 ]
591
592 for j in range(1, 20):
593 types = [
594 (f"struct_{j}_channel_0", np.uint8),
595 (f"struct_{j}_channel_1", np.uint16),
596 (f"struct_{j}_channel_2", np.uint32),
597 (f"struct_{j}_channel_3", np.uint64),
598 (f"struct_{j}_channel_4", np.int8),
599 (f"struct_{j}_channel_5", np.int16),
600 (f"struct_{j}_channel_6", np.int32),
601 (f"struct_{j}_channel_7", np.int64),
602 ]
603 dtype = np.dtype(types)
604
605 vals = mdf.get(f"Channel_{j}", group=i, samples_only=True)[0]
606 arrays = [arr * j for arr in samples_list]
607 target = np.rec.fromarrays(arrays, dtype=dtype)
608 if not np.array_equal(vals, target):
609 equal = False
610 raise Exception
611
612 self.assertTrue(equal)
613
614 def test_cut_demo(self) -> None:
615 print("MDF cut demo tests")
616
617 mdf_files = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix in (".mdf", ".mf4")]
618
619 signals = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix == ".npy"]
620
621 for file in mdf_files:
622 print(file)
623
624 for inp in (file, BytesIO(file.read_bytes())):
625 with MDF(inp, use_display_names=True) as input_file:
626 for whence in (0, 1):
627 print(file, whence)
628
629 cut = input_file.cut(stop=2, whence=whence, include_ends=False)
630 outfile1 = cut.save(Path(TestMDF.tempdir.name) / "tmp1", overwrite=True)
631 cut.close()
632
633 cut = input_file.cut(start=2, stop=6, whence=whence, include_ends=False)
634 outfile2 = cut.save(Path(TestMDF.tempdir.name) / "tmp2", overwrite=True)
635 cut.close()
636
637 cut = input_file.cut(start=6, whence=whence, include_ends=False)
638 outfile3 = cut.save(Path(TestMDF.tempdir.name) / "tmp3", overwrite=True)
639 cut.close()
640
641 concatenated = MDF.concatenate(
642 [outfile1, outfile2, outfile3],
643 version=input_file.version,
644 use_display_names=True,
645 )
646
647 outfile = concatenated.save(Path(TestMDF.tempdir.name) / "tmp", overwrite=True)
648
649 print("OUT", outfile)
650 concatenated.close()
651
652 with MDF(outfile, use_display_names=True) as mdf2:
653 for signal in signals:
654 target = np.load(signal)
655 sig = mdf2.get(signal.stem, *mdf2.whereis(signal.stem)[0])
656 timestamps = input_file.get(signal.stem, *input_file.whereis(signal.stem)[0]).timestamps
657
658 self.assertTrue(np.array_equal(sig.samples, target))
659 self.assertTrue(np.array_equal(timestamps, sig.timestamps))
660
661 if isinstance(inp, BytesIO):
662 inp.close()
663
664 @unittest.skipIf(sys.platform != "win32", "skip for unix for now")
665 def test_filter(self) -> None:
666 print("MDF read tests")
667
668 mdf_files = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix in (".mdf", ".mf4")]
669
670 signals = {file.stem: file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix == ".npy"}
671
672 for file in mdf_files:
673 print(file)
674
675 for inp in (file, BytesIO(file.read_bytes())):
676 with MDF(inp, use_display_names=True) as input_file:
677 names = [ch.name for gp in input_file.groups for ch in gp.channels[1:]]
678
679 channels_nr = np.random.randint(1, len(names) + 1)
680
681 channel_list = random.sample(names, channels_nr)
682
683 filtered_mdf = input_file.filter(channel_list)
684
685 target_names = set(filtered_mdf.channels_db)
686
687 self.assertFalse(set(channel_list) - (target_names - {"time"}))
688
689 for name in channel_list:
690 target = np.load(signals[name])
691 filtered = filtered_mdf.get(name)
692 self.assertTrue(np.array_equal(target, filtered.samples))
693
694 filtered_mdf.close()
695
696 if isinstance(inp, BytesIO):
697 inp.close()
698
699 def test_select(self) -> None:
700 print("MDF select tests")
701
702 mdf_files = [file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix in (".mdf", ".mf4")]
703
704 signals = {file.stem: file for file in Path(TestMDF.tempdir_demo.name).iterdir() if file.suffix == ".npy"}
705
706 for file in mdf_files:
707 print(file)
708
709 for inp in (file, BytesIO(file.read_bytes())):
710 with MDF(inp, use_display_names=True) as input_file:
711 names = [ch.name for gp in input_file.groups for ch in gp.channels[1:]]
712
713 input_file.configure(read_fragment_size=200)
714
715 channels_nr = np.random.randint(1, len(names) + 1)
716 channel_list = random.sample(names, channels_nr)
717
718 selected_signals = input_file.select(channel_list)
719
720 target_names = {s.name for s in selected_signals}
721
722 self.assertFalse(set(target_names) - set(channel_list))
723
724 for name, sig in zip(channel_list, selected_signals, strict=False):
725 target = np.load(signals[name])
726 self.assertTrue(np.array_equal(target, sig.samples))
727
728 if isinstance(inp, BytesIO):
729 inp.close()
730
731 def test_scramble(self) -> None:
732 print("MDF scramble tests")
733
734 for input_file in Path(TestMDF.tempdir_demo.name).iterdir():
735 if input_file.suffix.lower() in (".mdf", ".mf4"):
736 scrambled = MDF.scramble(input_file)
737 self.assertTrue(scrambled)
738 Path(scrambled).unlink()
739
740 def test_iter_groups(self) -> None:
741 dfs = [
742 DataFrame(
743 {
744 f"df_{i}_column_0": np.ones(5) * i,
745 f"df_{i}_column_1": np.arange(5) * i,
746 }
747 )
748 for i in range(5)
749 ]
750
751 mdf = MDF()
752 for df in dfs:
753 mdf.append(df)
754
755 for i, mdf_df in enumerate(mdf.iter_groups()):
756 self.assertTrue(mdf_df.equals(dfs[i]))
757
758 mdf.close()
759
760 def test_resample_raster_0(self) -> None:
761 sigs = [
762 Signal(
763 samples=np.ones(1000) * i,
764 timestamps=np.arange(1000),
765 name=f"Signal_{i}",
766 )
767 for i in range(20)
768 ]
769
770 mdf = MDF()
771 mdf.append(sigs)
772 mdf.configure(read_fragment_size=1)
773 with self.assertRaises(MdfException):
774 mdf = mdf.resample(raster=0)
775
776 mdf.close()
777
778 def test_resample(self) -> None:
779 raster = 1.33
780 sigs = [
781 Signal(
782 samples=np.arange(1000, dtype="f8"),
783 timestamps=np.concatenate([np.arange(500), np.arange(1000, 1500)]),
784 name=f"Signal_{i}",
785 )
786 for i in range(20)
787 ]
788
789 mdf = MDF()
790 mdf.append(sigs)
791 resampled = mdf.resample(raster=raster)
792 mdf.close()
793
794 target_timestamps = np.arange(0, 1500, 1.33)
795 target_samples = np.concatenate(
796 [
797 np.arange(0, 500, 1.33),
798 np.linspace(499.00215568862274, 499.9976646706587, 376),
799 np.arange(500.1600000000001, 1000, 1.33),
800 ]
801 )
802
803 for i, sig in enumerate(resampled.iter_channels(skip_master=True)):
804 self.assertTrue(np.array_equal(sig.timestamps, target_timestamps))
805 self.assertTrue(np.allclose(sig.samples, target_samples))
806
807 resampled.close()
808
809 def test_to_dataframe(self) -> None:
810 dfs = [
811 DataFrame(
812 {
813 f"df_{i}_column_0": np.ones(5) * i,
814 f"df_{i}_column_1": np.arange(5) * i,
815 }
816 )
817 for i in range(5)
818 ]
819
820 mdf = MDF()
821 for df in dfs:
822 mdf.append(df)
823
824 target: dict[str, npt.NDArray[Any]] = {}
825 for i in range(5):
826 target[f"df_{i}_column_0"] = np.ones(5) * i
827 target[f"df_{i}_column_1"] = np.arange(5) * i
828
829 df = DataFrame(target)
830
831 self.assertTrue(df.equals(mdf.to_dataframe()))
832 mdf.close()
833
834 def test_search(self) -> None:
835 sigs = [
836 Signal(
837 samples=np.ones(1),
838 timestamps=np.arange(1),
839 name=ch_name,
840 )
841 for ch_name in ["foo", "Bar", "baz"]
842 ]
843 mdf = MDF()
844 mdf.append(sigs)
845
846 # plain text matching
847 self.assertEqual(["foo"], mdf.search(pattern="foo"), msg="name match full")
848 self.assertEqual(["foo"], mdf.search(pattern="oo", mode="plain"), msg="name match part")
849 self.assertEqual(
850 [],
851 mdf.search(pattern="FOO", mode=SearchMode.plain, case_insensitive=False),
852 msg="name match case-sensitive (no match)",
853 )
854 self.assertEqual(
855 ["foo"],
856 mdf.search(pattern="FOO", mode=SearchMode.plain, case_insensitive=True),
857 msg="name match case-insensitive (match)",
858 )
859
860 # regex matching
861 self.assertEqual(["Bar"], mdf.search(pattern="^Bar$", mode="regex"), msg="regex match full")
862 self.assertEqual(
863 ["baz"],
864 mdf.search(pattern="z$", mode=SearchMode.regex),
865 msg="regex match part",
866 )
867 self.assertEqual(
868 ["baz"],
869 mdf.search(pattern="b.*", mode=SearchMode.regex, case_insensitive=False),
870 msg="regex match case-sensitive",
871 )
872 self.assertEqual(
873 ["Bar", "baz"],
874 mdf.search(pattern="b.*", mode=SearchMode.regex, case_insensitive=True),
875 msg="regex match case-insensitive",
876 )
877
878 # wildcard matching
879 self.assertEqual(
880 ["Bar"],
881 mdf.search(pattern="Bar", mode="wildcard"),
882 msg="wildcard match full",
883 )
884 self.assertEqual(
885 ["foo"],
886 mdf.search(pattern="*oo", mode=SearchMode.wildcard),
887 msg="wildcard match part",
888 )
889 self.assertEqual(
890 ["baz"],
891 mdf.search(pattern="b*", mode=SearchMode.wildcard, case_insensitive=False),
892 msg="wildcard match case-sensitive",
893 )
894 self.assertEqual(
895 ["Bar", "baz"],
896 mdf.search(pattern="b*", mode=SearchMode.wildcard, case_insensitive=True),
897 msg="wildcard match case-insensitive",
898 )
899
900
901 if __name__ == "__main__":
902 unittest.main()