Debian Codegraph @

nixio/test/test_nix_compatibility.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright © 2018, German Neuroinformatics Node (G-Node)
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted under the terms of the BSD License. See
8 # LICENSE file in the root of the Project.
9 import os
10 try:
11 from collections.abc import Iterable
12 except ImportError:
13 from collections import Iterable
14 from collections import OrderedDict
15 from subprocess import Popen, PIPE
16 import numpy as np
17 import pytest
18
19 import nixio as nix
20
21
22 dtypes = (
23 nix.DataType.UInt8,
24 nix.DataType.UInt16,
25 nix.DataType.UInt32,
26 nix.DataType.UInt64,
27 nix.DataType.Int8,
28 nix.DataType.Int16,
29 nix.DataType.Int32,
30 nix.DataType.Int64,
31 nix.DataType.Float,
32 nix.DataType.Double,
33 nix.DataType.String,
34 nix.DataType.Bool
35 )
36
37
38 def validate(fname):
39 """
40 Runs the nix validation function on the given file.
41 """
42 runcpp("validate", fname)
43
44
45 def runcpp(*cmdargs):
46 proc = Popen(cmdargs, stdout=PIPE, stderr=PIPE)
47 proc.wait()
48 stdout = proc.stdout.read().decode()
49 stderr = proc.stderr.read().decode()
50 if proc.returncode:
51 raise ValueError(stdout+stderr)
52
53
54 @pytest.mark.compatibility
55 def test_blocks(tmpdir, bindir):
56 nixfilepath = os.path.join(str(tmpdir), "blocktest.nix")
57 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
58 for idx in range(10):
59 blk = nix_file.create_block("test_block" + str(idx),
60 "blocktype")
61 blk.definition = "definition block " + str(idx)
62 blk.force_created_at(np.random.randint(1000000000))
63
64 nix_file.close()
65 # validate(nixfilepath)
66 cmd = os.path.join(bindir, "readblocks")
67 runcpp(cmd, nixfilepath)
68
69
70 @pytest.mark.compatibility
71 def test_groups(tmpdir, bindir):
72 nixfilepath = os.path.join(str(tmpdir), "grouptest.nix")
73 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
74 blk = nix_file.create_block("test_block", "blocktype")
75 for idx in range(12):
76 grp = blk.create_group("group_" + str(idx), "grouptype")
77 grp.definition = "group definition " + str(idx*10)
78 grp.force_created_at(np.random.randint(1000000000))
79
80 nix_file.close()
81 # validate(nixfilepath)
82 cmd = os.path.join(bindir, "readgroups")
83 runcpp(cmd, nixfilepath)
84
85
86 @pytest.mark.compatibility
87 def test_data_arrays(tmpdir, bindir):
88 nixfilepath = os.path.join(str(tmpdir), "arraytest.nix")
89 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
90 blk = nix_file.create_block("test_block", "blocktype")
91 grp = blk.create_group("test_group", "grouptype")
92
93 for idx in range(7):
94 da = blk.create_data_array("data_" + str(idx), "thedata",
95 data=np.arange(40, 80).reshape((2, 20)))
96 da.definition = "da definition " + str(idx)
97 da.force_created_at(np.random.randint(1000000000))
98 da.label = "data label " + str(idx)
99 da.unit = "mV"
100 da.expansion_origin = 0.0
101 if (idx % 2) == 0:
102 da.expansion_origin = 100.0
103 grp.data_arrays.append(da)
104 if (idx % 3) == 0:
105 da.polynom_coefficients = (0.1, 0.2, 0.3)
106 da.type = "somedataarray"
107 if idx == 5:
108 da.append_range_dimension([1.2, 2.4])
109 da.dimensions[0].unit = "ms"
110 if idx == 6:
111 da.append_set_dimension(["a", "b"])
112 da.append_sampled_dimension(1.0, 'dim_label', 's', 1.0)
113
114 nix_file.close()
115 # validate(nixfilepath)
116 cmd = os.path.join(bindir, "readdataarrays")
117 runcpp(cmd, nixfilepath)
118
119
120 @pytest.mark.compatibility
121 def test_data_frames(tmpdir, bindir):
122 nixfilepath = os.path.join(str(tmpdir), "frametest.nix")
123 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
124 blk = nix_file.create_block("test_block", "blocktype")
125 dt_full_list = [str, nix.DataType.Int64,
126 nix.DataType.Float, nix.DataType.Float, nix.DataType.Bool]
127
128 for idx in range(7):
129 col_names = ['name', 'id', 'exp1', 'exp2', 'Valid']
130 arr = [('Alice', 1234590, 1234.1245614e+9, 1034545e-8, False),
131 ('Bob', 9874542, 12.335205e-9, 123958e+9, True),
132 ('Jane', 9874542123, 12.5335205e-1, 123958e+29, True),
133 ('Chris', 9, 12.335205e-19, 123958e+19, False)]
134 df = blk.create_data_frame("df_" + str(idx), "df type " + str(idx),
135 col_names=col_names,
136 col_dtypes=dt_full_list,
137 data=arr)
138 df.force_created_at(np.random.randint(1000000000))
139 if idx == 4:
140 str_arr = ['119741023950123956123', 'asd908v*6a-sd', 'a'*50, ' ']
141 df.append_column(str_arr, "somelongstr", str)
142 elif idx == 5:
143 new_row = [('Dallas', 111, 123.445, 546.555, True)]
144 df.append_rows(new_row)
145 nix_file.close()
146 # validate(nixfilepath)
147 cmd = os.path.join(bindir, "readdataframes")
148 runcpp(cmd, nixfilepath)
149
150
151 @pytest.mark.compatibility
152 def test_tags(tmpdir, bindir):
153 nixfilepath = os.path.join(str(tmpdir), "tagtest.nix")
154 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
155 blk = nix_file.create_block("test_block", "blocktype")
156 grp = blk.create_group("test_group", "grouptype")
157 da1 = blk.create_data_array("feature_tag", "afea",
158 data=np.random.random_sample(20))
159
160 for idx in range(8):
161 if idx == 2:
162 tag = blk.create_tag("tag_" + str(idx), "atag",
163 [0, 10, 10**2, 10**3, 10**4])
164 else:
165 tag = blk.create_tag("tag_" + str(idx), "atag",
166 np.random.random_sample(idx*2))
167 tag.definition = "tag def " + str(idx)
168 if idx == 2:
169 tag.extent = np.random.random_sample(5)
170 else:
171 tag.extent = np.random.random_sample(idx*2)
172 if idx == 0:
173 tag.units = ["V", "ms"]
174 else:
175 tag.units = ["mV", "s"]
176 tag.force_created_at(np.random.randint(100000000))
177
178 if (idx % 3) == 0:
179 grp.tags.append(tag)
180
181 if idx == 5:
182 tag.create_feature(da1, nix.LinkType.Tagged)
183 nix_file.close()
184 # validate(nixfilepath)
185 cmd = os.path.join(bindir, "readtags")
186 runcpp(cmd, nixfilepath)
187
188
189 @pytest.mark.compatibility
190 def test_multi_tags(tmpdir, bindir):
191 nixfilepath = os.path.join(str(tmpdir), "mtagtest.nix")
192 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
193 blk = nix_file.create_block("test_block", "blocktype")
194 grp = blk.create_group("test_group", "grouptype")
195
196 for idx in range(11):
197 if idx == 5:
198 posda = blk.create_data_array("pos_" + str(idx), "positions",
199 data=np.random.random_sample((idx, idx)))
200 extda = blk.create_data_array("ext_" + str(idx), "extents",
201 data=np.random.random_sample((idx, idx)))
202
203 else:
204 posda = blk.create_data_array("pos_" + str(idx), "positions",
205 data=np.random.random_sample(idx*10))
206 extda = blk.create_data_array("ext_" + str(idx), "extents",
207 data=np.random.random_sample(idx*10))
208 mt = blk.create_multi_tag("mt_" + str(idx), "some multi tag", posda)
209 if idx == 3:
210 feada = blk.create_data_array("feature", "afea",
211 data=np.random.random_sample(200))
212 mt.create_feature(feada, nix.LinkType.Tagged)
213
214 if idx != 1:
215 mt.extents = extda
216 if idx == 2:
217 refda = blk.create_data_array("ref", "reference",
218 data=np.random.random_sample(13))
219 refda.append_range_dimension([0.1, 0.2, 0.3], "A", "s")
220 mt.references.append(refda)
221 mt.units = ["ms"]
222 else:
223 mt.units = ["mV", "s", "Hz"]
224
225 if (idx % 3) == 0:
226 grp.multi_tags.append(mt)
227 mt.definition = "mt def " + str(idx*10)
228 mt.force_created_at(np.random.randint(100000000))
229 nix_file.close()
230 # validate(nixfilepath)
231 cmd = os.path.join(bindir, "readmultitags")
232 runcpp(cmd, nixfilepath)
233
234
235 @pytest.mark.compatibility
236 def _test_sources(tmpdir):
237 nixfilepath = os.path.join(str(tmpdir), "sourcetest.nix")
238 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
239 blk = nix_file.create_block("testblock", "sourcetest")
240 grp = blk.create_group("testgroup", "sourcetest")
241 da = blk.create_data_array("da", "sourcetest",
242 data=np.random.random_sample(10))
243 pos = blk.create_data_array("pos", "sourcetest",
244 data=np.random.random_sample(10))
245 mtag = blk.create_multi_tag("mtag", "sourcetest", pos)
246 grp.data_arrays.append(da)
247
248 for idx in range(20):
249 src = blk.create_source("src" + str(idx), "source")
250 src_child = src.create_source("child src " + str(idx), "source")
251
252 if (idx % 5) == 0:
253 grp.sources.append(src)
254
255 if (idx % 3) == 0:
256 mtag.sources.append(src_child)
257
258 if (idx % 8) == 0:
259 da.sources.append(src)
260
261 # TODO: Nested sources
262
263 nix_file.close()
264 # validate(nixfilepath)
265
266
267 @pytest.mark.compatibility
268 def _test_dimensions(tmpdir):
269 nixfilepath = os.path.join(str(tmpdir), "dimtest.nix")
270 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
271 blk = nix_file.create_block("testblock", "dimtest")
272
273 da_set = blk.create_data_array("da with set", "datype",
274 data=np.random.random_sample(20))
275 da_set.append_set_dimension()
276 da_set.dimensions[0].labels = ["label one", "label two"]
277
278 da_range = blk.create_data_array("da with range", "datype",
279 data=np.random.random_sample(12))
280 rngdim = da_range.append_range_dimension(np.random.random_sample(12))
281 rngdim.label = "range dim label"
282 rngdim.unit = "ms"
283
284 da_sample = blk.create_data_array("da with sample", "datype",
285 data=np.random.random_sample(10))
286 smpldim = da_sample.append_sampled_dimension(0.3)
287 smpldim.offset = 0.1
288 smpldim.unit = "mV"
289
290 da_sample.dimensions[0].label = "sample dim label"
291
292 da_alias = blk.create_data_array("da with alias", "datype",
293 data=np.random.random_sample(19))
294 da_alias.unit = "F"
295 da_alias.label = "fee fi fo fum"
296 da_alias.append_alias_range_dimension()
297
298 da_multi_dim = blk.create_data_array("da with multiple", "datype",
299 data=np.random.random_sample(30))
300 da_multi_dim.append_sampled_dimension(0.1)
301 da_multi_dim.append_set_dimension()
302 da_multi_dim.append_range_dimension(np.random.random_sample(10))
303
304 nix_file.close()
305 # validate(nixfilepath)
306
307
308 @pytest.mark.compatibility
309 def _test_tag_features(tmpdir):
310 nixfilepath = os.path.join(str(tmpdir), "feattest.nix")
311 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
312 blk = nix_file.create_block("testblock", "feattest")
313 da_ref = blk.create_data_array("da for ref", "datype",
314 nix.DataType.Double,
315 data=np.random.random_sample(15))
316 da_ref.append_sampled_dimension(0.2)
317 tag_feat = blk.create_tag("tag for feat", "tagtype", [2])
318 tag_feat.references.append(da_ref)
319
320 linktypes = [nix.LinkType.Tagged, nix.LinkType.Untagged,
321 nix.LinkType.Indexed]
322 for idx in range(6):
323 da_feat = blk.create_data_array("da for feat " + str(idx),
324 "datype", nix.DataType.Float,
325 data=np.random.random_sample(12))
326 da_feat.append_sampled_dimension(1.0)
327 tag_feat.create_feature(da_feat, linktypes[idx % 3])
328
329 nix_file.close()
330 # validate(nixfilepath)
331
332
333 @pytest.mark.compatibility
334 def test_multi_tag_features(tmpdir):
335 nixfilepath = os.path.join(str(tmpdir), "mtagfeattest.nix")
336 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
337 blk = nix_file.create_block("testblock", "mtfeattest")
338 index_data = blk.create_data_array(
339 "indexed feature data", "test",
340 dtype=nix.DataType.Double, shape=(10, 10)
341 )
342 dim1 = index_data.append_sampled_dimension(1.0)
343 dim1.unit = "ms"
344 dim2 = index_data.append_sampled_dimension(1.0)
345 dim2.unit = "ms"
346
347 data1 = np.zeros((10, 10))
348 total = 0.0
349 for i in range(10):
350 value = 100 * i
351 for j in range(10):
352 value += 1
353 data1[i, j] = value
354 total += data1[i, j]
355
356 index_data[:, :] = data1
357
358 tagged_data = blk.create_data_array(
359 "tagged feature data", "test",
360 dtype=nix.DataType.Double, shape=(10, 20, 10)
361 )
362 dim1 = tagged_data.append_sampled_dimension(1.0)
363 dim1.unit = "ms"
364 dim2 = tagged_data.append_sampled_dimension(1.0)
365 dim2.unit = "ms"
366 dim3 = tagged_data.append_sampled_dimension(1.0)
367 dim3.unit = "ms"
368
369 data2 = np.zeros((10, 20, 10))
370 for i in range(10):
371 value = 100 * i
372 for j in range(20):
373 for k in range(10):
374 value += 1
375 data2[i, j, k] = value
376
377 tagged_data[:, :, :] = data2
378
379 event_labels = ["event 1", "event 2"]
380 dim_labels = ["dim 0", "dim 1", "dim 2"]
381 event_array = blk.create_data_array("positions", "test",
382 data=np.random.random_sample((2, 3)))
383 extent_array = blk.create_data_array("extents", "test",
384 data=np.random.random_sample((2, 3)))
385 extent_set_dim = extent_array.append_set_dimension()
386 extent_set_dim.labels = event_labels
387 extent_set_dim = extent_array.append_set_dimension()
388 extent_set_dim.labels = dim_labels
389
390 feature_tag = blk.create_multi_tag("feature_tag", "events",
391 event_array)
392 data_array = blk.create_data_array("featureTest", "test",
393 nix.DataType.Double, (2, 10, 5))
394 data = np.random.random_sample((2, 10, 5))
395 data_array[:, :, :] = data
396
397 feature_tag.extents = extent_array
398
399 feature_tag.create_feature(index_data, nix.LinkType.Indexed)
400 feature_tag.create_feature(tagged_data, nix.LinkType.Tagged)
401 feature_tag.create_feature(index_data, nix.LinkType.Untagged)
402
403 nix_file.close()
404 # validate(nixfilepath)
405
406
407 @pytest.mark.compatibility
408 def test_multi_tag_references(tmpdir):
409 nixfilepath = os.path.join(str(tmpdir), "blocktest.nix")
410 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
411 interval = 0.001
412 data_x = np.arange(0, 10, interval)
413 data_y = np.sin(2*np.pi*data_x)
414 blk = nix_file.create_block("blk", "reftest")
415 da = blk.create_data_array("sin", "data", data=data_y)
416 da.unit = "dB"
417 dim = da.append_sampled_dimension(interval)
418 dim.unit = "s"
419
420 pos = blk.create_data_array("pos1", "positions", data=np.array([[0]]))
421 pos.append_set_dimension()
422 pos.append_set_dimension()
423 pos.unit = "ms"
424 ext = blk.create_data_array("ext1", "extents",
425 data=np.array([[2000]]))
426 ext.append_set_dimension()
427 ext.append_set_dimension()
428 ext.unit = "ms"
429
430 mtag = blk.create_multi_tag("sin1", "tag", pos)
431 mtag.extents = ext
432 mtag.units = ["ms"]
433 mtag.references.append(da)
434
435 nix_file.close()
436 # validate(nixfilepath)
437
438
439 @pytest.mark.compatibility
440 def test_properties(tmpdir):
441 nixfilepath = os.path.join(str(tmpdir), "proptest.nix")
442 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
443 sec = nix_file.create_section("test section", "proptest")
444 sec.create_property("test property", 0)
445 sec.create_property("test str", nix.DataType.String)
446 sec.create_property("other property", nix.DataType.Int64)
447
448 sec.create_property("prop Int32", nix.DataType.Int32)
449 sec.create_property("prop Int64", nix.DataType.Int64)
450 sec.create_property("prop UInt32", nix.DataType.UInt32)
451 sec.create_property("prop UInt64", nix.DataType.UInt64)
452 sec.create_property("prop Float", nix.DataType.Float)
453 sec.create_property("prop Double", nix.DataType.Double)
454 sec.create_property("prop String", nix.DataType.String)
455 sec.create_property("prop Bool", nix.DataType.Bool)
456
457 sec.props[1].definition = "def"
458
459 sec.props[0].values = [101]
460 sec.props[1].values = ["foo", "bar", "baz"]
461 sec.props["prop Float"].values = np.array([10.0, 33.3, 1.345, 90.2],
462 dtype=nix.DataType.Float)
463
464 nix_file.close()
465 # validate(nixfilepath)
466
467
468 @pytest.mark.compatibility
469 def test_sections(tmpdir):
470 nixfilepath = os.path.join(str(tmpdir), "sectiontest.nix")
471 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
472 for idx in range(30):
473 sec = nix_file.create_section("test section" + str(idx),
474 "sectiontest")
475 sec.definition = "sec definition " + str(idx)
476 sec.repository = "sec repo" + str(idx * 3)
477
478 nested_sec = sec.create_section("nested_section", "sec")
479 if (idx % 3) == 0:
480 lvl2 = nested_sec.create_section("level 2", "sec")
481
482 if (idx % 12) == 0:
483 lvl2.create_section("level 3", "sec")
484
485 block = nix_file.create_block("block", "section test")
486 block.metadata = nix_file.sections[0].sections[0].sections[0]
487
488 nix_file.close()
489 # validate(nixfilepath)
490
491
492 @pytest.mark.compatibility
493 def test_full_write(tmpdir):
494 # Create a fully-featured nix file
495 nixfilepath = os.path.join(str(tmpdir), "fulltest.nix")
496 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
497 for idx in range(30):
498 sec = nix_file.create_section("test section" + str(idx),
499 "sectiontest")
500 sec.definition = "sec definition " + str(idx)
501 sec.repository = "sec repo" + str(idx * 3)
502
503 nested_sec = sec.create_section("nested_section", "sec")
504 if (idx % 3) == 0:
505 lvl2 = nested_sec.create_section("level 2", "sec")
506
507 if (idx % 12) == 0:
508 lvl2.create_section("level 3", "sec")
509
510 block = nix_file.create_block("block", "section test")
511 block.metadata = nix_file.sections[0].sections[0].sections[0]
512
513 nix_file.close()
514 # validate(nixfilepath)
515
516
517 @pytest.mark.compatibility
518 def test_full_file_write(tmpdir, bindir):
519 nixfilepath = os.path.join(str(tmpdir), "filetest-writepy.nix")
520 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.Overwrite)
521
522 block = nix_file.create_block("blockyblock", "ablocktype of thing")
523 block.definition = "I am a test block"
524 block.force_created_at(1500001000)
525
526 scndblk = nix_file.create_block("I am another block", "void")
527 scndblk.definition = "Void block of stuff"
528 scndblk.force_created_at(1500002000)
529
530 thrdblk = nix_file.create_block("Block C", "a block of stuff")
531 thrdblk.definition = "The third block"
532 thrdblk.force_created_at(1500003000)
533
534 for idx, block in enumerate(nix_file.blocks):
535 group = block.create_group("grp{:02}0".format(idx), "grp")
536 group.definition = "grp{:02}0-grp".format(idx)
537 group.force_created_at(block.created_at)
538 group = block.create_group("grp{:02}1".format(idx), "grp")
539 group.definition = "grp{:02}1-grp".format(idx)
540 group.force_created_at(block.created_at)
541
542 block = nix_file.blocks[0]
543 da = block.create_data_array("bunchodata", "recordings",
544 dtype=nix.DataType.Double,
545 data=[[1, 2, 10], [9, 1, 3]])
546 da.definition = "A silly little data array"
547 smpldim = da.append_sampled_dimension(0.1)
548 smpldim.unit = "ms"
549 smpldim.label = "time"
550 setdim = da.append_set_dimension()
551 setdim.labels = ["a", "b"]
552 group = block.groups[0]
553 group.data_arrays.append(da)
554
555 df = block.create_data_frame("adataframe", "4-column df",
556 col_dict=OrderedDict([('name', str),
557 ('id', int),
558 ('time', float),
559 ('Adjusted', bool)]),
560 data=[["Bob", 9, 11.28, False],
561 ["Jane", 10, 14.37, True]])
562 df.append_rows([["Alice", 2, 3.7, False]])
563
564 featda = block.create_data_array("feat-da", "tag-feature",
565 data=[0.4, 0.41, 0.49, 0.1, 0.1, 0.1])
566
567 tag = block.create_tag("tagu", "tagging", position=[1, 0])
568 tag.extent = [1, 10]
569 tag.units = ["mV", "s"]
570 tag.definition = "tags ahoy"
571 tag.references.append(da)
572 group.tags.append(tag)
573 # TODO: Every other kind of link
574 tag.create_feature(featda, nix.LinkType.Untagged)
575
576 mtag = block.create_multi_tag("mtagu", "multi tagging",
577 positions=block.create_data_array(
578 "tag-data", "multi-tagger",
579 data=[[0, 0.1, 10.1]]
580 ))
581 # MultiTag positions array
582 block.data_arrays["tag-data"].append_sampled_dimension(0.01)
583 block.data_arrays["tag-data"].dimensions[0].unit = "s"
584 block.data_arrays["tag-data"].append_set_dimension()
585
586 # MultiTag extents array
587 mtag.extents = block.create_data_array("tag-extents", "multi-tagger",
588 data=[[0.5, 0.5, 0.5]])
589 block.data_arrays["tag-extents"].append_sampled_dimension(0.01)
590 block.data_arrays["tag-extents"].dimensions[0].unit = "s"
591 block.data_arrays["tag-extents"].append_set_dimension()
592
593 da = nix_file.blocks[1].create_data_array("FA001", "Primary data",
594 dtype=np.int64,
595 data=[100, 200, 210, 4])
596 da.definition = "Some random integers"
597
598 # Source tree
599 block = nix_file.blocks[0]
600 src = block.create_source("root-source", "top-level-source")
601 # point all (block's) data arrays to root-source
602 for da in block.data_arrays:
603 da.sources.append(src)
604
605 srcd1 = src.create_source("d1-source", "second-level-source")
606 src.create_source("d1-source-2", "second-level-source")
607 # point first da to d1-source
608 block.data_arrays[0].sources.append(srcd1)
609
610 # Metadata
611 # 3 root sections
612 for name in ["mda", "mdb", "mdc"]:
613 nix_file.create_section(name, "root-section")
614
615 sec = nix_file.sections["mdc"]
616 # 6 sections under third root section
617 for idx in range(6):
618 sec.create_section("{:03}-md".format(idx), "d1-section")
619
620 # Point existing objects to metadata sections
621 nix_file.blocks[0].metadata = nix_file.sections["mdb"]
622 nix_file.blocks[2].metadata = nix_file.sections["mdb"]
623
624 nix_file.blocks[1].data_arrays[0].metadata = nix_file.sections["mda"]
625 nix_file.blocks[0].tags[0].metadata = nix_file.sections["mdc"].sections[3]
626
627 # Add Tag and MultiTag to Block 2, Group 0
628 block = nix_file.blocks[2]
629 group = block.groups[0]
630 tag = block.create_tag("POI", "TAG", position=[0, 0])
631 tag.extent = [1920, 1080]
632 tag.units = ["mm", "mm"]
633
634 png = block.create_data_array("some-sort-of-image?", "png",
635 shape=(3840, 2160))
636 tag.create_feature(png, nix.LinkType.Indexed)
637
638 newmtpositions = block.create_data_array("nu-pos", "multi-tag-positions",
639 shape=(10, 3),
640 dtype=nix.DataType.Double)
641 newmtag = block.create_multi_tag("nu-mt", "multi-tag (new)",
642 positions=newmtpositions)
643 group.tags.append(tag)
644 group.multi_tags.append(newmtag)
645
646 # Data with RangeDimension
647 block = nix_file.blocks[2]
648 da = block.create_data_array("the ticker", "range-dim-array",
649 dtype=nix.DataType.Int32,
650 data=[0, 1, 23])
651 da.unit = "uA"
652 ticks = np.arange(10, 15, 0.1)
653 rdim = da.append_range_dimension(ticks)
654 rdim.label = "a range dimension"
655 rdim.unit = "s"
656
657 # Alias RangeDimension
658 block = nix_file.blocks[1]
659 da = block.create_data_array("alias da", "dimticks",
660 data=np.arange(3, 15, 0.5))
661 da.label = "alias dimension label"
662 da.unit = "F"
663 da.append_alias_range_dimension()
664
665 # All types of metadata
666 mdb = nix_file.sections["mdb"]
667 proptypesmd = mdb.create_section("prop-test-parent",
668 "test metadata section")
669 numbermd = proptypesmd.create_section("numerical metadata",
670 "test metadata section")
671 numbermd["integer"] = 42
672 numbermd["double"] = 4.2
673 numbermd["integers"] = [40, 41, 42, 43, 44, 45]
674 numbermd["doubles"] = [1.1, 10.10]
675
676 othermd = proptypesmd.create_section("other metadata",
677 "test metadata section")
678 othermd["bool"] = True
679 othermd["false bool"] = False
680 othermd["bools"] = [True, False, True]
681 othermd["string"] = "I am a string. Rawr."
682 othermd["strings"] = ["one", "two", "twenty"]
683 othermd["unicode"] = ["Μπύρα", "Bräu", "啤酒", "🍺"]
684
685 # All types of data
686 dtypeblock = nix_file.create_block("datablock", "block of data")
687
688 for idx, dt in enumerate(dtypes):
689 dtypeblock.create_data_array(str(idx), "dtype-test-array",
690 dtype=dt, data=dt(0))
691
692 # Unicode DataArray on last Block
693 data = ["Καφές", "Café", "咖啡", "☕"]
694 dtypeblock.create_data_array("unicodedata", "coffeestuff",
695 dtype=nix.DataType.String,
696 data=data)
697
698 nix_file.close()
699 cmd = os.path.join(bindir, "readfullfile")
700 runcpp(cmd, nixfilepath)
701 # validate(nixfilepath)
702
703
704 def check_block_children_counts(block, ngrp, nda, ntg, nmt):
705 assert ngrp == len(block.groups),\
706 "Group count mismatch in Block {}".format(block.name)
707 assert nda == len(block.data_arrays),\
708 "DataArray count mismatch in Block {}".format(block.name)
709 assert ntg == len(block.tags),\
710 "Tag count mismatch in Block {}".format(block.name)
711 assert nmt == len(block.multi_tags),\
712 "MultiTag count mismatch in Block {}".format(block.name)
713
714
715 def check_group_children_counts(group, nda, ntg, nmt):
716 assert nda == len(group.data_arrays),\
717 "DataArray count mismatch in Group {}".format(group.name)
718 assert ntg == len(group.tags),\
719 "Tag count mismatch in Group {}".format(group.name)
720 assert nmt == len(group.multi_tags),\
721 "MultiTag count mismatch in Group {}".format(group.name)
722
723
724 def compare(expected, actual):
725 if (isinstance(expected, Iterable) and
726 isinstance(actual, Iterable) and not
727 isinstance(expected, str)):
728 assert len(expected) == len(actual), "Expected {}, got {}".format(expected, actual)
729 for exp, act in zip(expected, actual):
730 compare(exp, act)
731 return
732 assert expected == actual, "Expected {}, got {}".format(expected, actual)
733
734
735 @pytest.mark.compatibility
736 def test_full_file_read(tmpdir, bindir):
737 nixfilepath = os.path.join(str(tmpdir), "filetest-readpy.nix")
738 cmd = os.path.join(bindir, "writefullfile")
739 runcpp(cmd, nixfilepath)
740 nix_file = nix.File.open(nixfilepath, mode=nix.FileMode.ReadOnly)
741
742 # Check object counts
743 assert 4 == len(nix_file.blocks), "Block count mismatch"
744 check_block_children_counts(nix_file.blocks[0], 2, 4, 1, 1)
745 check_block_children_counts(nix_file.blocks[1], 2, 2, 0, 0)
746 check_block_children_counts(nix_file.blocks[2], 2, 3, 1, 1)
747 check_block_children_counts(nix_file.blocks[3], 0, 13, 0, 0)
748
749 check_group_children_counts(nix_file.blocks[0].groups[0], 1, 1, 0)
750 check_group_children_counts(nix_file.blocks[0].groups[1], 0, 0, 0)
751
752 check_group_children_counts(nix_file.blocks[1].groups[0], 0, 0, 0)
753 check_group_children_counts(nix_file.blocks[1].groups[1], 0, 0, 0)
754
755 check_group_children_counts(nix_file.blocks[2].groups[0], 0, 1, 1)
756 check_group_children_counts(nix_file.blocks[2].groups[1], 0, 0, 0)
757
758 block = nix_file.blocks[0]
759 # Check first block attrs before descending
760 compare("blockyblock", block.name)
761 compare("ablocktype of thing", block.type)
762 compare("I am a test block", block.definition)
763
764 block = nix_file.blocks[1]
765 # Check second block attrs (no children)
766 compare("I am another block", block.name)
767 compare("void", block.type)
768 compare("Void block of stuff", block.definition)
769
770 for bidx, block in enumerate(nix_file.blocks):
771 for gidx, group in enumerate(block.groups):
772 compare("grp0{}{}".format(bidx, gidx), group.name)
773 compare("grp", group.type)
774 compare("group {}".format(gidx), group.definition)
775 compare(block.created_at, group.created_at)
776
777 # DataArray
778 block = nix_file.blocks[0]
779 group = block.groups[0]
780
781 da = block.data_arrays[0]
782 compare(da.id, group.data_arrays[0].id)
783 compare("bunchodata", da.name)
784 compare("recordings", da.type)
785 compare("A silly little data array", da.definition)
786
787 # Data
788 compare([[1., 2., 10.], [9., 1., 3.]], da[:])
789 compare([2, 3], da.shape)
790 compare(nix.DataType.Double, da.data_type)
791
792 # DataArray dimensions
793 dim = da.dimensions[0]
794 compare(nix.DimensionType.Sample, dim.dimension_type)
795 compare(0.1, dim.sampling_interval)
796 compare("ms", dim.unit)
797 compare("time", dim.label)
798
799 dim = da.dimensions[1]
800 compare(nix.DimensionType.Set, dim.dimension_type)
801 compare(["a", "b"], dim.labels)
802
803 # Data Frame
804 df = block.data_frames[0]
805 compare("table", df.name)
806 compare("filing", df.type)
807 dt = (nix.util.util.vlen_str_dtype,
808 nix.DataType.Double, nix.DataType.Int64, nix.DataType.Bool)
809 compare(dt, df.dtype)
810 col_name = ("str", "Double", "int64", "bool")
811 compare(col_name, df.column_names)
812 combine_dt = np.dtype([(n, dty) for n, dty in zip(col_name, dt)])
813 arr = np.array([(b"exp1", 42.1, 10, False),
814 (b"exp2", 30.2, 4, True)], dtype=combine_dt)
815 compare(arr, df[:])
816 # could not test shape because it will write data
817
818 # Tag
819 tag = block.tags[0]
820 compare("tagu", tag.name)
821 compare("tagging", tag.type)
822 compare("tags ahoy", tag.definition)
823 compare([1, 0], tag.position)
824 compare([1, 10], tag.extent)
825 compare(["mV", "s"], tag.units)
826 compare(da.id, tag.references[0].id)
827 compare(group.tags[0].id, tag.id)
828 feature = tag.features["feat-da"]
829 compare(nix.LinkType.Untagged, feature.link_type)
830 compare(feature.data.id, block.data_arrays[1].id)
831 compare("feat-da", feature.data.name)
832 compare((6,), feature.data.shape)
833 compare([0.4, 0.41, 0.49, 0.1, 0.1, 0.1], feature.data[:])
834
835 # MultiTag
836 mtag = block.multi_tags[0]
837 compare("mtagu", mtag.name)
838 compare("multi tagging", mtag.type)
839 compare(None, mtag.definition)
840 posmt = mtag.positions
841 extmt = mtag.extents
842 compare(posmt.id, block.data_arrays[posmt.name].id)
843 compare(extmt.id, block.data_arrays[extmt.name].id)
844
845 # MultiTag data
846 compare("tag-data", posmt.name)
847 compare("multi-tagger", posmt.type)
848 compare("tag-extents", extmt.name)
849 compare("multi-tagger", extmt.type)
850
851 compare([1, 3], posmt.shape)
852 compare([[0, 0.1, 10.1]], posmt[:])
853 compare(nix.DataType.Double, posmt.data_type)
854
855 compare([1, 3], extmt.shape)
856 compare([[0.5, 0.5, 0.5]], extmt[:])
857 compare(nix.DataType.Double, extmt.data_type)
858
859 # MultiTag Position and Extent dimensions
860 compare(2, len(posmt.dimensions))
861 dim = posmt.dimensions[1]
862 compare(nix.DimensionType.Set, dim.dimension_type)
863
864 dim = posmt.dimensions[0]
865 compare(nix.DimensionType.Sample, dim.dimension_type)
866 compare(0.01, dim.sampling_interval)
867 compare("s", dim.unit)
868
869 compare(2, len(extmt.dimensions))
870 dim = extmt.dimensions[1]
871 compare(nix.DimensionType.Set, dim.dimension_type)
872
873 dim = extmt.dimensions[0]
874 compare(nix.DimensionType.Sample, dim.dimension_type)
875 compare(0.01, dim.sampling_interval)
876 compare("s", dim.unit)
877
878 # Tag and MultiTag Block and Group membership
879 for idx in range(1, len(nix_file.blocks)):
880 assert tag.id not in nix_file.blocks[idx].tags,\
881 "Tag found in incorrect Block"
882 assert mtag.id not in nix_file.blocks[idx].multi_tags,\
883 "MultiTag found in incorrect Block"
884
885 group = block.groups[0]
886 assert mtag.id not in group.multi_tags, "MultiTag found in incorrect Group"
887 for idx in range(1, len(block.groups)):
888 assert tag.id not in block.groups[idx].tags, "Tag found in incorrect Group"
889 assert mtag.id not in block.groups[idx].multi_tags, "MultiTag found in incorrect Group"
890
891 # Second block DataArray
892 block = nix_file.blocks[1]
893 da = block.data_arrays[0]
894 compare("FA001", da.name)
895 compare("Primary data", da.type)
896 compare(nix.DataType.Int64, da.data_type)
897
898 # Sources
899 block = nix_file.blocks[0]
900 compare(1, len(block.sources))
901 src = block.sources["root-source"]
902 compare("top-level-source", src.type)
903 for da in block.data_arrays:
904 compare(da.sources[0].id, src.id)
905
906 compare(2, len(src.sources))
907 compare("d1-source", src.sources[0].name)
908 compare("d1-source-2", src.sources[1].name)
909 compare("second-level-source", src.sources[0].type)
910 compare("second-level-source", src.sources[1].type)
911
912 for chsrc in src.sources:
913 compare(0, len(chsrc.sources))
914
915 da = block.data_arrays[0]
916 compare(2, len(da.sources))
917 compare(da.sources[1].id, block.sources[0].sources[0].id)
918
919 # Metadata
920 # 3 root sections
921 compare(3, len(nix_file.sections))
922 compare("mda", nix_file.sections[0].name)
923 compare("mdb", nix_file.sections[1].name)
924 compare("mdc", nix_file.sections[2].name)
925 for chsec in nix_file.sections:
926 compare("root-section", chsec.type)
927
928 mdc = nix_file.sections[2]
929 compare(6, len(mdc.sections))
930 for idx in range(6):
931 compare("d1-section", mdc.sections["{:03d}-md".format(idx)].type)
932
933 mdb = nix_file.sections[1]
934 compare(nix_file.blocks[0].metadata.id, mdb.id)
935 compare(nix_file.blocks[2].metadata.id, mdb.id)
936
937 compare(nix_file.blocks[1].data_arrays[0].metadata.id,
938 nix_file.sections["mda"].id)
939 compare(nix_file.blocks[0].tags[0].metadata.id,
940 nix_file.sections["mdc"].sections[3].id)
941
942 block = nix_file.blocks[2]
943 tag = block.tags[0]
944 compare("POI", tag.name)
945 compare("TAG", tag.type)
946 compare([0, 0], tag.position)
947 compare([1920, 1080], tag.extent)
948 compare(["mm", "mm"], tag.units)
949 compare(tag.id, block.groups[0].tags[0].id)
950
951 feature = tag.features["some-sort-of-image?"]
952 compare(nix.LinkType.Indexed, feature.link_type)
953 compare(feature.data.id, block.data_arrays[0].id)
954 compare("some-sort-of-image?", feature.data.name)
955 compare([3840, 2160], feature.data.shape)
956
957 mtag = block.multi_tags[0]
958 compare("nu-mt", mtag.name)
959 compare("multi-tag (new)", mtag.type)
960 posmt = mtag.positions
961 compare("nu-pos", posmt.name)
962 compare("multi-tag-positions", posmt.type)
963 compare([10, 3], posmt.shape)
964 compare(nix.DataType.Double, posmt.data_type)
965 compare(posmt.id, block.data_arrays[1].id)
966 compare(mtag.id, block.groups[0].multi_tags[0].id)
967
968 # Data with range dimension
969 block = nix_file.blocks[2]
970 da = block.data_arrays["the ticker"]
971 compare([0, 1, 23], da[:])
972 compare([3], da.shape)
973 compare("range-dim-array", da.type)
974 compare("uA", da.unit)
975 compare(nix.DataType.Int32, da.data_type)
976 dim = da.dimensions[0]
977 compare(nix.DimensionType.Range, dim.dimension_type)
978
979 # Alias range dimension
980 block = nix_file.blocks[1]
981 da = block.data_arrays["alias da"]
982 compare("dimticks", da.type)
983 compare("F", da.unit)
984 compare("alias dimension label", da.label)
985 compare([24], da.shape)
986 dim = da.dimensions[0]
987 compare(nix.DimensionType.Range, dim.dimension_type)
988 assert dim.is_alias
989 compare(da[:], dim.ticks)
990
991 # Metadata types
992 mdb = nix_file.sections["mdb"]
993 compare(1, len(mdb.sections))
994 proptypesmd = mdb.sections["prop-test-parent"]
995 compare("test metadata section", proptypesmd.type)
996 compare(2, len(proptypesmd.sections))
997
998 numbermd = proptypesmd.sections[0]
999 compare("numerical metadata", numbermd.name)
1000 compare("test metadata section", numbermd.type)
1001 compare(4, len(numbermd.props))
1002
1003 prop = numbermd.props["integer"]
1004 compare(1, len(prop.values))
1005 compare([42], prop.values)
1006
1007 prop = numbermd.props["float"]
1008 compare(1, len(prop.values))
1009 # TODO: Almost equal
1010 # compare([4.2], prop.values)
1011
1012 prop = numbermd.props["integers"]
1013 compare(6, len(prop.values))
1014 compare([40+v for v in range(6)], prop.values)
1015
1016 prop = numbermd.props["floats"]
1017 compare(2, len(prop.values))
1018 # TODO: Almost equal
1019
1020 othermd = proptypesmd.sections[1]
1021 compare("other metadata", othermd.name)
1022 compare("test metadata section", othermd.type)
1023 compare(6, len(othermd.props))
1024
1025 prop = othermd.props["bool"]
1026 compare(1, len(prop.values))
1027 compare([True], prop.values)
1028
1029 prop = othermd.props["false bool"]
1030 compare(1, len(prop.values))
1031 compare([False], prop.values)
1032
1033 prop = othermd.props["bools"]
1034 compare(3, len(prop.values))
1035 compare([True, False, True], prop.values)
1036
1037 prop = othermd.props["string"]
1038 compare(1, len(prop.values))
1039 compare(["I am a string. Rawr."], prop.values)
1040
1041 prop = othermd.props["strings"]
1042 compare(3, len(prop.values))
1043 compare(["one", "two", "twenty"], prop.values)
1044
1045 prop = othermd.props["unicode"]
1046 compare(4, len(prop.values))
1047 compare(["Μπύρα", "Bräu", "啤酒", "🍺"], prop.values)
1048
1049 block = nix_file.blocks["datablock"]
1050 for idx in range(len(dtypes)):
1051 print(da.name)
1052 da = block.data_arrays[idx]
1053 dt = dtypes[idx]
1054 if dt == nix.DataType.String:
1055 dt = nix.util.vlen_str_dtype
1056 compare(dt, da.data_type)
1057 compare([0], da.shape)
1058
1059 da = block.data_arrays["unicodedata"]
1060 unicodedata = ["Καφές", "Café", "咖啡", "☕"]
1061 dadata = da[:]
1062 compare(unicodedata, dadata)
1063
1064 nix_file.close()
1065 # validate(nixfilepath)