File: test_utils.py

package info (click to toggle)
python-nxtomomill 2.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,340 kB
  • sloc: python: 17,207; makefile: 15; sh: 3
file content (1267 lines) | stat: -rw-r--r-- 52,785 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
# coding: utf-8

from __future__ import annotations

import os
import shutil
import tempfile
import unittest

import h5py
import numpy.random

from silx.io.url import DataUrl
from silx.io.utils import h5py_read_dataset

from tomoscan.io import HDF5File, get_swmr_mode
from tomoscan.esrf.mock import MockNXtomo as MockNXtomo
from tomoscan.esrf.scan.nxtomoscan import NXtomoScan

from nxtomo.nxobject.nxdetector import ImageKey

from nxtomomill.utils import add_dark_flat_nx_file, change_image_key_control


class MockNXtomoWithElecCurrent(MockNXtomo):
    def __init__(
        self,
        scan_path,
        ini_dark: numpy.array | None,
        ini_flats: numpy.array | None,
        final_flats: numpy.array | None,
        dim: int,
        n_proj: int,
        count_time: numpy.array | None = None,
        machine_current: numpy.array | None = None,
    ):
        assert ini_dark is None or ini_dark.ndim == 3, "ini_dark should be a 3d array"
        assert ini_flats is None or ini_flats.ndim == 3, "ini_dark should be a 3d array"
        assert (
            final_flats is None or final_flats.ndim == 3
        ), "ini_dark should be a 3d array"
        self._ini_darks = ini_dark
        self._ini_flats = ini_flats
        self._final_flats = final_flats
        self._count_time = count_time
        super().__init__(
            scan_path=scan_path,
            dim=dim,
            create_ini_dark=ini_dark is not None,
            create_ini_flat=ini_flats is not None,
            create_final_flat=final_flats is not None,
            n_ini_proj=n_proj,
            n_proj=n_proj,
        )

        # append count_time and machine_current to the HDF5 file
        with HDF5File(self.scan_master_file, "a") as h5_file:
            entry_one = h5_file.require_group(self.scan_entry)
            if machine_current is not None:
                monitor_grp = entry_one.require_group("control")
                monitor_grp["data"] = machine_current
            # rewrite count_time
            if count_time is not None:
                instrument_grp = entry_one.require_group("instrument")
                detector_grp = instrument_grp.require_group("detector")
                if "count_time" in detector_grp:
                    del detector_grp["count_time"]
                detector_grp["count_time"] = count_time

    def add_initial_dark(self):
        for frame in self._ini_darks:
            self._append_frame(
                data_=frame.reshape(1, frame.shape[0], frame.shape[1]),
                rotation_angle=self.rotation_angle[-1],
                image_key=ImageKey.DARK_FIELD.value,
                image_key_control=ImageKey.DARK_FIELD.value,
                diode_data=None,
            )

    def add_initial_flat(self):
        for frame in self._ini_flats:
            self._append_frame(
                data_=frame.reshape(1, frame.shape[0], frame.shape[1]),
                rotation_angle=self.rotation_angle[-1],
                image_key=ImageKey.FLAT_FIELD.value,
                image_key_control=ImageKey.FLAT_FIELD.value,
                diode_data=None,
            )

    def add_final_flat(self):
        for frame in self._final_flats:
            self._append_frame(
                data_=frame.reshape(1, frame.shape[0], frame.shape[1]),
                rotation_angle=self.rotation_angle[-1],
                image_key=ImageKey.FLAT_FIELD.value,
                image_key_control=ImageKey.FLAT_FIELD.value,
                diode_data=None,
            )


class BaseTestAddDarkAndFlats(unittest.TestCase):
    """
    Unit test on nxtomomill.utils.add_dark_flat_nx_file function
    """

    def setUp(self) -> None:
        self.tmpdir = tempfile.mkdtemp()
        simple_nx_path = os.path.join(self.tmpdir, "simple_case")
        self.dim = 55
        self.nproj = 20
        self._simple_nx = MockNXtomoWithElecCurrent(
            scan_path=simple_nx_path,
            n_proj=self.nproj,
            ini_dark=None,
            ini_flats=None,
            final_flats=None,
            dim=self.dim,
            machine_current=numpy.zeros(self.nproj),
        ).scan
        with HDF5File(
            self._simple_nx.master_file, mode="r", swmr=get_swmr_mode()
        ) as h5s:
            data_path = "/".join(
                (self._simple_nx.entry, "instrument", "detector", "data")
            )
            self._raw_data = h5py_read_dataset(h5s[data_path])
        nx_with_vds_path = os.path.join(self.tmpdir, "case_with_vds")
        self._nx_with_virtual_dataset = MockNXtomoWithElecCurrent(
            scan_path=nx_with_vds_path,
            n_proj=0,
            ini_dark=None,
            ini_flats=None,
            final_flats=None,
            dim=self.dim,
            machine_current=numpy.zeros(self.nproj),
        ).scan
        self._create_vds(
            source_file=self._simple_nx.master_file,
            source_data_path=self._simple_nx.entry,
            target_file=self._nx_with_virtual_dataset.master_file,
            target_data_path=self._nx_with_virtual_dataset.entry,
            copy_other_data=True,
        )
        self._patch_nxtomo_flags(self._nx_with_virtual_dataset)

        nx_with_vds_path_and_links = os.path.join(
            self.tmpdir, "case_with_vds_and_links"
        )
        self._nx_with_virtual_dataset_with_link = MockNXtomoWithElecCurrent(
            scan_path=nx_with_vds_path_and_links,
            n_proj=0,
            ini_dark=None,
            ini_flats=None,
            final_flats=None,
            dim=self.dim,
            machine_current=numpy.zeros(self.nproj),
        ).scan
        self._create_vds(
            source_file=self._simple_nx.master_file,
            source_data_path=self._simple_nx.entry,
            target_file=self._nx_with_virtual_dataset_with_link.master_file,
            target_data_path=self._nx_with_virtual_dataset_with_link.entry,
            copy_other_data=True,
        )
        self._patch_nxtomo_flags(self._nx_with_virtual_dataset_with_link)

        # create dark
        self.start_dark = (
            numpy.random.random((self.dim * self.dim))
            .reshape(1, self.dim, self.dim)
            .astype("f")
        )
        self.start_dark_file = os.path.join(self.tmpdir, "dark.hdf5")
        self.start_dark_entry = "data"
        self.start_dark_url = self._save_raw(
            data=self.start_dark,
            entry=self.start_dark_entry,
            file_path=self.start_dark_file,
        )

        self.end_dark = (
            numpy.random.random((self.dim * self.dim * 2))
            .reshape(2, self.dim, self.dim)
            .astype("f")
        )
        self.end_dark_file = os.path.join(self.tmpdir, "dark.hdf5")
        self.end_dark_entry = "data2"
        self.end_dark_url = self._save_raw(
            data=self.end_dark, entry=self.end_dark_entry, file_path=self.end_dark_file
        )

        # create flats
        self.start_flat = (
            numpy.random.random((self.dim * self.dim * 3))
            .reshape(3, self.dim, self.dim)
            .astype("f")
        )
        self.start_flat_file = os.path.join(self.tmpdir, "start_flat.hdf5")
        self.start_flat_entry = "/root/flat"
        self.start_flat_url = self._save_raw(
            data=self.start_flat,
            entry=self.start_flat_entry,
            file_path=self.start_flat_file,
        )

        self.end_flat = (
            numpy.random.random((self.dim * self.dim))
            .reshape(1, self.dim, self.dim)
            .astype("f")
        )
        # save the end flat in the simple case file to insure all cases are
        # consider
        self.end_flat_file = self._simple_nx.master_file
        self.end_flat_entry = "flat"
        self.end_flat_url = self._save_raw(
            data=self.end_flat, entry=self.end_flat_entry, file_path=self.end_flat_file
        )

    def _save_raw(self, data, entry, file_path) -> DataUrl:
        with HDF5File(file_path, mode="a") as h5s:
            h5s[entry] = data
        return DataUrl(file_path=file_path, data_path=entry, scheme="silx")

    def _create_vds(
        self,
        source_file: str,
        source_data_path: str,
        target_file: str,
        target_data_path: str,
        copy_other_data: bool,
    ):
        """Create virtual dataset and links from source to target

        :param source_file:
        :param source_data_path:
        :param target_file:
        :param target_data_path:
        :param copy_other_data: we want to create two cases: one copying
                                     datasets 'image_key'... and the other
                                     one linking them. Might have a difference
                                     of behavior when overwriting for example
        """
        assert source_file != target_file, "file should be different"
        # link data
        n_frames = 0
        # for now we only consider the original data
        with HDF5File(source_file, mode="r", swmr=get_swmr_mode()) as o_h5s:
            old_path = os.path.join(source_data_path, "instrument", "detector", "data")
            n_frames += o_h5s[old_path].shape[0]
            shape = o_h5s[old_path].shape
            data_type = o_h5s[old_path].dtype

            layout = h5py.VirtualLayout(shape=shape, dtype=data_type)
            assert os.path.exists(source_file)
            with HDF5File(source_file, mode="r", swmr=get_swmr_mode()) as ppp:
                assert source_data_path in ppp
            layout[:] = h5py.VirtualSource(path_or_dataset=o_h5s[old_path])

            det_path = os.path.join(target_data_path, "instrument", "detector")
            with HDF5File(target_file, mode="a") as h5s:
                detector_node = h5s.require_group(det_path)
                detector_node.create_virtual_dataset("data", layout, fillvalue=-5)

        for path in (
            os.path.join("instrument", "detector", "image_key"),
            os.path.join("instrument", "detector", "image_key_control"),
            os.path.join("instrument", "detector", "count_time"),
            os.path.join("sample", "rotation_angle"),
        ):
            old_path = os.path.join(source_data_path, path)
            new_path = os.path.join(target_data_path, path)
            with HDF5File(target_file, mode="a") as h5s:
                if copy_other_data:
                    with HDF5File(source_file, mode="r", swmr=get_swmr_mode()) as o_h5s:
                        if new_path in h5s:
                            del h5s[new_path]
                        h5s[new_path] = h5py_read_dataset(o_h5s[old_path])
                elif source_file == target_file:
                    h5s[new_path] = h5py.SoftLink(old_path)
                else:
                    relpath = os.path.relpath(source_file, os.path.dirname(target_file))
                    h5s[new_path] = h5py.ExternalLink(relpath, old_path)

    def _patch_nxtomo_flags(self, scan):
        """Insure necessary flags are here"""
        with HDF5File(scan.master_file, mode="a") as h5s:
            instrument_path = os.path.join(scan.entry, "instrument")
            instrument_node = h5s.require_group(instrument_path)
            if "NX_class" not in instrument_node.attrs:
                instrument_node.attrs["NX_class"] = "NXinstrument"
            detector_node = instrument_node.require_group("detector")
            if "NX_class" not in detector_node.attrs:
                detector_node.attrs["NX_class"] = "NXdetector"
            if "data" in instrument_node:
                if "interpretation" not in instrument_node.attrs:
                    instrument_node["data"].attrs["interpretation"] = "image"

            sample_path = os.path.join(scan.entry, "sample")
            sample_node = h5s.require_group(sample_path)
            if "NX_class" not in sample_node:
                sample_node.attrs["NX_class"] = "NXsample"

    def tearDown(self) -> None:
        shutil.rmtree(self.tmpdir)


class TestAddDarkAtStart(BaseTestAddDarkAndFlats):
    """
    Make sure adding dark works
    """

    def testAddDarkAsNumpyArray(self) -> None:
        """Insure adding a dark works from a numpy array"""
        for scan in (self._simple_nx,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    darks_start=self.start_dark,
                )

                # test `data` dataset
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape, (self.nproj + 1, self.dim, self.dim)
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self.start_dark[0]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][1], self._raw_data[0]
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)

        # test some exception are raised if we try to add directly a numpy
        # array within a virtual dataset
        for scan in (
            self._nx_with_virtual_dataset,
            self._nx_with_virtual_dataset_with_link,
        ):
            with self.assertRaises(TypeError):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    darks_start=self.start_dark,
                )

    def testAddDarkAsDataUrl(self) -> None:
        """Insure adding a dark works from a DataUrl"""
        for scan in (self._nx_with_virtual_dataset_with_link,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    darks_start=self.start_dark_url,
                )

                # test `data` dataset
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape, (self.nproj + 1, self.dim, self.dim)
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self.start_dark[0]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][1], self._raw_data[0]
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)
                    # test rotation angle and count_time
                    count_time_path = os.path.join(
                        scan.entry, "instrument", "detector", "count_time"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[count_time_path][-1]), 1
                    )
                    self.assertEqual(
                        len(h5s[count_time_path]), self.nproj + self.start_dark.shape[0]
                    )
                    rotation_angle_path = os.path.join(
                        scan.entry, "sample", "rotation_angle"
                    )
                    numpy.testing.assert_array_equal(
                        h5s[rotation_angle_path][0], h5s[rotation_angle_path][1]
                    )
                    self.assertEqual(
                        len(h5s[rotation_angle_path]),
                        self.nproj + self.start_dark.shape[0],
                    )
                    control_data_path = os.path.join(scan.entry, "control", "data")
                    numpy.testing.assert_array_equal(
                        h5s[control_data_path][0], h5s[control_data_path][1]
                    )
                    self.assertEqual(
                        len(h5s[control_data_path]),
                        self.nproj + self.start_dark.shape[0],
                    )


class TestAddFlatAtStart(BaseTestAddDarkAndFlats):
    """
    Make sure adding initial flat works
    """

    def testAddFlatStartAsNumpyArray(self) -> None:
        """Insure adding a dark works from a numpy array"""
        for scan in (self._simple_nx,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_start=self.start_flat,
                )

                # test `data` dataset
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape,
                        (self.nproj + self.start_flat.shape[0], self.dim, self.dim),
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self.start_flat[0]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][2], self.start_flat[2]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][3], self._raw_data[0]
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)

        # test some exception are raised if we try to add directly a numpy
        # array within a virtual dataset
        for scan in (
            self._nx_with_virtual_dataset,
            self._nx_with_virtual_dataset_with_link,
        ):
            with self.assertRaises(TypeError):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_start=self.start_flat,
                )

    def testAddFlatStartAsDataUrl(self) -> None:
        """Insure adding a dark works from a DataUrl"""
        for scan in (self._nx_with_virtual_dataset_with_link,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_start=self.start_flat_url,
                )

                # test `data` dataset
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape,
                        (self.nproj + self.start_flat.shape[0], self.dim, self.dim),
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self.start_flat[0]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][2], self.start_flat[2]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][3], self._raw_data[0]
                    )
                    # test rotation angle and count_time
                    count_time_path = os.path.join(
                        scan.entry, "instrument", "detector", "count_time"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[count_time_path][-1]), 1
                    )
                    self.assertEqual(
                        len(h5s[count_time_path]), self.nproj + self.start_flat.shape[0]
                    )
                    rotation_angle_path = os.path.join(
                        scan.entry, "sample", "rotation_angle"
                    )
                    numpy.testing.assert_array_equal(
                        h5s[rotation_angle_path][0], h5s[rotation_angle_path][1]
                    )
                    self.assertEqual(
                        len(h5s[rotation_angle_path]),
                        self.nproj + self.start_flat.shape[0],
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)


class TestAddFlatAtEnd(BaseTestAddDarkAndFlats):
    """
    Make sure adding final flat works
    """

    def testAddFlatEndAsNumpyArray(self) -> None:
        """Insure adding a dark works from a numpy array"""
        for scan in (self._simple_nx,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_end=self.end_flat,
                )

                # test `data` dataset
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape,
                        (self.nproj + self.end_flat.shape[0], self.dim, self.dim),
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][-1], self.end_flat[-1]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self._raw_data[0]
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)

                    # test the 'image_key' and image_key_control dataset
                    img_key_control_path = os.path.join(
                        scan.entry, "instrument", "detector", "image_key_control"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[img_key_control_path][-2:]), [0, 1]
                    )
                    img_key_path = os.path.join(
                        scan.entry, "instrument", "detector", "image_key"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[img_key_path][-2:]), [0, 1]
                    )
                    # test rotation angle and count_time
                    count_time_path = os.path.join(
                        scan.entry, "instrument", "detector", "count_time"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[count_time_path][-1]), 1
                    )
                    self.assertEqual(
                        len(h5s[count_time_path]), self.nproj + self.end_flat.shape[0]
                    )
                    rotation_angle_path = os.path.join(
                        scan.entry, "sample", "rotation_angle"
                    )
                    numpy.testing.assert_array_equal(
                        h5s[rotation_angle_path][-1], h5s[rotation_angle_path][-2]
                    )
                    self.assertEqual(
                        len(h5s[rotation_angle_path]),
                        self.nproj + self.end_flat.shape[0],
                    )

        # test some exception are raised if we try to add directly a numpy
        # array within a virtual dataset
        for scan in (
            self._nx_with_virtual_dataset,
            self._nx_with_virtual_dataset_with_link,
        ):
            with self.assertRaises(TypeError):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_end=self.end_flat,
                )

    def testAddFlatStartAsDataUrl(self) -> None:
        """Insure adding a dark works from a DataUrl"""
        for scan in (self._nx_with_virtual_dataset_with_link,):
            with self.subTest(scan=scan):
                add_dark_flat_nx_file(
                    file_path=scan.master_file,
                    entry=scan.entry,
                    flats_end=self.end_flat_url,
                )

                # test data is correctly store
                with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
                    # test the 'data' dataset
                    data_path = os.path.join(
                        scan.entry, "instrument", "detector", "data"
                    )
                    self.assertEqual(
                        h5s[data_path].shape,
                        (self.nproj + self.end_flat.shape[0], self.dim, self.dim),
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][-1], self.end_flat[-1]
                    )
                    numpy.testing.assert_array_almost_equal(
                        h5s[data_path][0], self._raw_data[0]
                    )
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)
                    # test the 'image_key' and image_key_control dataset
                    img_key_control_path = os.path.join(
                        scan.entry, "instrument", "detector", "image_key_control"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[img_key_control_path][-2:]), [0, 1]
                    )
                    img_key_path = os.path.join(
                        scan.entry, "instrument", "detector", "image_key"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[img_key_path][-2:]), [0, 1]
                    )
                    # test rotation angle and count_time
                    count_time_path = os.path.join(
                        scan.entry, "instrument", "detector", "count_time"
                    )
                    numpy.testing.assert_array_equal(
                        h5py_read_dataset(h5s[count_time_path][-1]), 1
                    )
                    self.assertEqual(
                        len(h5s[count_time_path]), self.nproj + self.end_flat.shape[0]
                    )
                    rotation_angle_path = os.path.join(
                        scan.entry, "sample", "rotation_angle"
                    )
                    numpy.testing.assert_array_equal(
                        h5s[rotation_angle_path][-1], h5s[rotation_angle_path][-2]
                    )
                    self.assertEqual(
                        len(h5s[rotation_angle_path]),
                        self.nproj + self.end_flat.shape[0],
                    )
                    # insure we can still make a HDF5Scan out of it
                    NXtomoScan(scan=scan.master_file, entry=scan.entry)


class TestAddDarkAndFlatWithFancySelection(BaseTestAddDarkAndFlats):
    """Insure we can do some fancy selection with virtual dataset and data url"""

    def testValid(self):
        """
        Insure virtual dataset are still correctly recreate even if
        using slices
        """
        scan = self._nx_with_virtual_dataset_with_link

        start_flat_url = DataUrl(
            file_path=self.start_flat_file,
            data_path=self.start_flat_entry,
            data_slice=slice(0, 4),
            scheme="silx",
        )
        end_dark_url = DataUrl(
            file_path=self.end_dark_file,
            data_path=self.end_dark_entry,
            data_slice=[
                1,
            ],
            scheme="silx",
        )

        add_dark_flat_nx_file(
            file_path=scan.master_file,
            entry=scan.entry,
            flats_start=start_flat_url,
            darks_end=end_dark_url,
            embed_data=False,
        )

        # test data is correctly store
        with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            # test the 'data' dataset
            data_path = os.path.join(scan.entry, "instrument", "detector", "data")
            self.assertEqual(
                h5s[data_path].shape,
                (self.nproj + 3 + 1, self.dim, self.dim),
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][0:3], self.start_flat[0:3]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-1], self.end_dark[1]
            )
            NXtomoScan(scan=scan.master_file, entry=scan.entry)
            # test the 'image_key' and image_key_control dataset
            img_key_control_path = os.path.join(
                scan.entry, "instrument", "detector", "image_key_control"
            )
            numpy.testing.assert_array_equal(
                h5py_read_dataset(h5s[img_key_control_path][0:3]), [1, 1, 1]
            )
            numpy.testing.assert_array_equal(
                h5py_read_dataset(h5s[img_key_control_path][-2:]), [0, 2]
            )
            # insure we can still make a HDF5Scan out of it
            NXtomoScan(scan=scan.master_file, entry=scan.entry)

    def testInValidSlice(self):
        """Insure an error is raise if user try to
        provide a slice with step !=1. This case is not handled
        """
        scan = self._nx_with_virtual_dataset_with_link

        start_flat_url = DataUrl(
            file_path=self.start_flat_file,
            data_path=self.start_flat_entry,
            data_slice=slice(0, 4, 2),
            scheme="silx",
        )
        end_dark_url = DataUrl(
            file_path=self.end_dark_file,
            data_path=self.end_dark_entry,
            data_slice=[
                1,
            ],
            scheme="silx",
        )
        with self.assertRaises(ValueError):
            add_dark_flat_nx_file(
                file_path=scan.master_file,
                entry=scan.entry,
                flats_start=start_flat_url,
                darks_end=end_dark_url,
                embed_data=False,
            )


class TestCompleteAddFlatAndDark(BaseTestAddDarkAndFlats):
    """
    Complete test on adding dark and flats on a complete case
    """

    def testWithoutExtras(self):
        """Insure a complete case can be handle without defining any extras
        parameters"""
        scan = self._nx_with_virtual_dataset_with_link

        add_dark_flat_nx_file(
            file_path=scan.master_file,
            entry=scan.entry,
            flats_start=self.start_flat_url,
            flats_end=self.end_flat_url,
            darks_start=self.start_dark_url,
            extras={},
        )
        with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            # test the 'data' dataset
            data_path = os.path.join(scan.entry, "instrument", "detector", "data")
            th_shape = (
                self.nproj
                + self.end_flat.shape[0]
                + self.start_flat.shape[0]
                + self.start_dark.shape[0],
                self.dim,
                self.dim,
            )
            self.assertEqual(h5s[data_path].shape, th_shape)

            # test the 'image_key' and image_key_control dataset
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][0], self.start_dark[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][1], self.start_flat[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-1], self.end_flat[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-self.end_flat.shape[0] - 1], self._raw_data[-1]
            )

            # test image_key
            img_key_path = os.path.join(
                scan.entry, "instrument", "detector", "image_key"
            )
            th_img_keys = [0] * self.nproj
            [th_img_keys.insert(0, 1) for _ in range(self.start_flat.shape[0])]
            [th_img_keys.insert(0, 2) for _ in range(self.start_dark.shape[0])]
            [th_img_keys.append(1) for _ in range(self.end_flat.shape[0])]

            numpy.testing.assert_array_equal(h5s[img_key_path], th_img_keys)
            # test rotation_angle dataset
            rotation_angle_dataset = os.path.join(
                scan.entry, "sample", "rotation_angle"
            )
            numpy.testing.assert_array_almost_equal(
                h5s[rotation_angle_dataset][0], h5s[rotation_angle_dataset][1]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[rotation_angle_dataset][0], h5s[rotation_angle_dataset][2]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[rotation_angle_dataset][-2], h5s[rotation_angle_dataset][-1]
            )

    def testWithExtras(self):
        """Insure a complete case can be handle providing some extras
        parameters"""
        scan = self._nx_with_virtual_dataset
        dark_extras = {"rotation_angle": 10.2}
        start_flat_extras = {"rotation_angle": [10, 11, 12]}
        end_flat_extras = {"count_time": 0.3}
        end_dark_extras = {"count_time": [0.1, 0.2], "rotation_angle": [89, 88]}

        extras = {
            "darks_start": dark_extras,
            "darks_end": end_dark_extras,
            "flats_start": start_flat_extras,
            "flats_end": end_flat_extras,
        }
        add_dark_flat_nx_file(
            file_path=scan.master_file,
            entry=scan.entry,
            flats_start=self.start_flat_url,
            flats_end=self.end_flat_url,
            darks_start=self.start_dark_url,
            darks_end=self.end_dark_url,
            extras=extras,
        )
        with HDF5File(scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            # test the 'data' dataset
            data_path = os.path.join(scan.entry, "instrument", "detector", "data")
            th_shape = (
                self.nproj
                + self.end_flat.shape[0]
                + self.start_flat.shape[0]
                + self.start_dark.shape[0]
                + self.end_dark.shape[0],
                self.dim,
                self.dim,
            )
            self.assertEqual(h5s[data_path].shape, th_shape)

            # test the 'image_key' and image_key_control dataset
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][0], self.start_dark[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][1], self.start_flat[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-1], self.end_flat[0]
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-self.end_flat.shape[0] - self.end_dark.shape[0] - 1],
                self._raw_data[-1],
            )
            numpy.testing.assert_array_almost_equal(
                h5s[data_path][-3], self.end_dark[-2]
            )

            # test image_key
            img_key_path = os.path.join(
                scan.entry, "instrument", "detector", "image_key"
            )
            th_img_keys = [0] * self.nproj
            [th_img_keys.insert(0, 1) for _ in range(self.start_flat.shape[0])]
            [th_img_keys.insert(0, 2) for _ in range(self.start_dark.shape[0])]
            [th_img_keys.append(2) for _ in range(self.end_dark.shape[0])]
            [th_img_keys.append(1) for _ in range(self.end_flat.shape[0])]

            numpy.testing.assert_array_equal(h5s[img_key_path], th_img_keys)
            # test rotation_angle dataset
            rotation_angle_dataset = os.path.join(
                scan.entry, "sample", "rotation_angle"
            )
            numpy.testing.assert_array_almost_equal(
                h5s[rotation_angle_dataset][0], 10.2
            )
            numpy.testing.assert_array_almost_equal(h5s[rotation_angle_dataset][-3], 89)
            numpy.testing.assert_array_almost_equal(
                h5py_read_dataset(h5s[rotation_angle_dataset][1:4]),
                numpy.array([10, 11, 12]),
            )
            numpy.testing.assert_array_almost_equal(
                h5s[rotation_angle_dataset][-2], h5s[rotation_angle_dataset][-1]
            )
            count_time_dataset = os.path.join(
                scan.entry, "instrument", "detector", "count_time"
            )
            self.assertEqual(h5s[count_time_dataset][-1], 0.3)
            self.assertEqual(h5s[count_time_dataset][-2], 0.2)
            self.assertEqual(h5s[count_time_dataset][0], 1)


class TestChangeImageKeyControl(unittest.TestCase):
    """
    Test the `change_image_key_control` function
    """

    def setUp(self) -> None:
        self.tmpdir = tempfile.mkdtemp()
        simple_nx_path = os.path.join(self.tmpdir, "simple_case")
        self.dim = 55
        self.nproj = 20
        # this can will have one dark, then 4 flats then 20 projections
        # then 4 flats and 5 alignment projections at the end
        mock = MockNXtomo(
            scan_path=simple_nx_path,
            n_proj=self.nproj,
            n_ini_proj=self.nproj,
            create_ini_dark=True,
            create_ini_flat=True,
            create_final_flat=True,
            dim=self.dim,
            n_refs=4,
        )
        n_alignment = 5
        for i in range(n_alignment):
            mock.add_alignment_radio(i, angle=0)
        self.scan = mock.scan

    def tearDown(self) -> None:
        if os.path.exists(self.tmpdir):
            shutil.rmtree(self.tmpdir)

    def testInputType(self):
        """Check a TypeError is raised if input of `frames_indexes` is
        invalid"""
        with self.assertRaises(TypeError):
            change_image_key_control(
                file_path=self.scan.master_file,
                entry=self.scan.entry,
                frames_indexes=1,
                image_key_control_value=ImageKey.PROJECTION,
            )

    def testUpdateToProjections(self):
        """Insure we can correctly set some frame as `projection`"""
        change_image_key_control(
            file_path=self.scan.master_file,
            entry=self.scan.entry,
            frames_indexes=slice(0, 3, 2),
            image_key_control_value=ImageKey.PROJECTION,
        )
        with HDF5File(self.scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            image_keys_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key")
            )
            image_keys = h5s[image_keys_path]
            image_keys_control_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key_control")
            )
            self.assertEqual(image_keys[0], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys[1], ImageKey.FLAT_FIELD.value)
            self.assertEqual(image_keys[2], ImageKey.PROJECTION.value)

            image_keys_control = h5s[image_keys_control_path]
            self.assertEqual(image_keys_control[0], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys_control[1], ImageKey.FLAT_FIELD.value)
            self.assertEqual(image_keys_control[2], ImageKey.PROJECTION.value)

    def testUpdateToDark(self):
        """Insure we can correctly set some frame as `dark`"""
        change_image_key_control(
            file_path=self.scan.master_file,
            entry=self.scan.entry,
            frames_indexes=[1],
            image_key_control_value=ImageKey.DARK_FIELD,
        )
        with HDF5File(self.scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            image_keys_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key")
            )
            image_keys = h5s[image_keys_path]
            image_keys_control_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key_control")
            )
            self.assertEqual(image_keys[0], ImageKey.DARK_FIELD.value)
            self.assertEqual(image_keys[1], ImageKey.DARK_FIELD.value)
            self.assertEqual(image_keys[2], ImageKey.FLAT_FIELD.value)

            image_keys_control = h5s[image_keys_control_path]
            self.assertEqual(image_keys_control[0], ImageKey.DARK_FIELD.value)
            self.assertEqual(image_keys_control[1], ImageKey.DARK_FIELD.value)
            self.assertEqual(image_keys_control[2], ImageKey.FLAT_FIELD.value)

    def testUpdateToFlat(self):
        """Insure we can correctly set some frame as `flatfield`"""
        change_image_key_control(
            file_path=self.scan.master_file,
            entry=self.scan.entry,
            frames_indexes=[0],
            image_key_control_value=ImageKey.FLAT_FIELD,
        )
        with HDF5File(self.scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            image_keys_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key")
            )
            image_keys = h5s[image_keys_path]
            image_keys_control_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key_control")
            )
            self.assertEqual(image_keys[0], ImageKey.FLAT_FIELD.value)
            self.assertEqual(image_keys[1], ImageKey.FLAT_FIELD.value)

            image_keys_control = h5s[image_keys_control_path]
            self.assertEqual(image_keys_control[0], ImageKey.FLAT_FIELD.value)
            self.assertEqual(image_keys_control[1], ImageKey.FLAT_FIELD.value)

    def testUpdateToAlignment(self):
        """Insure we can correctly set some frame as `alignment`"""
        change_image_key_control(
            file_path=self.scan.master_file,
            entry=self.scan.entry,
            frames_indexes=slice(10, 20, None),
            image_key_control_value=ImageKey.ALIGNMENT,
        )
        with HDF5File(self.scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            image_keys_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key")
            )
            image_keys = h5s[image_keys_path]
            image_keys_control_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key_control")
            )
            self.assertEqual(image_keys[10], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys[11], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys[20], ImageKey.PROJECTION.value)

            image_keys_control = h5s[image_keys_control_path]
            self.assertEqual(image_keys_control[9], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys_control[10], ImageKey.ALIGNMENT.value)
            self.assertEqual(image_keys_control[11], ImageKey.ALIGNMENT.value)
            self.assertEqual(image_keys_control[21], ImageKey.PROJECTION.value)

    def testUpdateToInvalid(self):
        """Insure we can correctly set some frame as `invalid`"""
        change_image_key_control(
            file_path=self.scan.master_file,
            entry=self.scan.entry,
            frames_indexes=slice(0, 16, 5),
            image_key_control_value=ImageKey.INVALID,
        )
        with HDF5File(self.scan.master_file, mode="r", swmr=get_swmr_mode()) as h5s:
            image_keys_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key")
            )
            image_keys = h5s[image_keys_path]
            image_keys_control_path = "/".join(
                (self.scan.entry, "instrument", "detector", "image_key_control")
            )
            self.assertEqual(image_keys[9], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys[10], ImageKey.INVALID.value)
            self.assertEqual(image_keys[11], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys[15], ImageKey.INVALID.value)

            image_keys_control = h5s[image_keys_control_path]
            self.assertEqual(image_keys_control[9], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys_control[10], ImageKey.INVALID.value)
            self.assertEqual(image_keys_control[11], ImageKey.PROJECTION.value)
            self.assertEqual(image_keys_control[15], ImageKey.INVALID.value)


class TestAddDarkAndFlatFromADifferentFolderWithVDS(unittest.TestCase):
    """
    Test adding dark and flat to vds pointing to vds pointing on files at
    at different level of the file system.
                               root_folder
            _______________________|_____________
           |                                    |
       folder_1                              folder_2
           |                                    |
      file created      _________________________|___________________
                       |               |                            |
                  subfolder_21     subfolder_22                 file with
                       |               |                    original start dark
               File containing     ____|___________
              VDS pointing to     |               |
              original flat    File with     subsubfolder_221
              and dark         original              |
                               start flat   File with original
                                               end flat
    """

    def setUp(self) -> None:
        unittest.TestCase.setUp(self)
        self.dim = 20
        # create folder
        self.root_folder = tempfile.mkdtemp()
        self.mv_folder = tempfile.mkdtemp()
        self.folder_1 = os.path.join(self.root_folder, "folder_1")
        self.folder_2 = os.path.join(self.root_folder, "folder_2")
        self.subfolder_21 = os.path.join(self.root_folder, "subfolder_21")
        self.subfolder_22 = os.path.join(self.root_folder, "subfolder_22")
        self.subsubfolder_221 = os.path.join(self.root_folder, "subsubfolder_221")
        for folder in (
            self.folder_1,
            self.folder_2,
            self.subfolder_21,
            self.subfolder_22,
            self.subsubfolder_221,
        ):
            os.makedirs(folder)

        # create original dark
        self.start_dark = (
            numpy.random.random((5 * self.dim * self.dim))
            .reshape(5, self.dim, self.dim)
            .astype("f")
        )
        self.start_dark_file = os.path.join(self.folder_2, "original_start_dark.hdf5")
        with HDF5File(self.start_dark_file, mode="w") as h5s:
            h5s["dark"] = self.start_dark
        self.start_dark_url = DataUrl(
            file_path=self.start_dark_file, data_path="dark", scheme="silx"
        )

        # create original flats
        self.start_flat = (
            numpy.random.random((5 * self.dim * self.dim))
            .reshape(5, self.dim, self.dim)
            .astype("f")
        )
        self.start_flat_file = os.path.join(self.subfolder_22, "original_start_flat.h5")
        with HDF5File(self.start_flat_file, mode="w") as h5s:
            h5s["flat1"] = self.start_flat
        self.start_flat_url = DataUrl(
            file_path=self.start_flat_file, data_path="flat1", scheme="silx"
        )

        self.end_flat = (
            numpy.random.random((5 * self.dim * self.dim))
            .reshape(5, self.dim, self.dim)
            .astype("f")
        )
        self.end_flat_file = os.path.join(self.subsubfolder_221, "original_end_flat.h5")
        with HDF5File(self.end_flat_file, mode="w") as h5s:
            h5s["flat2"] = self.end_flat
        self.end_flat_url = DataUrl(
            file_path=self.end_flat_file, data_path="flat2", scheme="silx"
        )

    def tearDown(self) -> None:
        for folder in (self.root_folder, self.mv_folder):
            if os.path.exists(folder):
                shutil.rmtree(folder)
        unittest.TestCase.tearDown(self)

    def test(self):
        # create a scan contained in subfolder21
        scan_subfolder_21 = self._simple_nx = MockNXtomo(
            scan_path=self.subfolder_21,
            n_proj=10,
            n_ini_proj=2,
            create_ini_dark=False,
            create_ini_flat=False,
            create_final_flat=False,
            dim=self.dim,
        ).scan
        # 1. add first level of indirection for dark and flat and check the VDS
        add_dark_flat_nx_file(
            file_path=scan_subfolder_21.master_file,
            entry=scan_subfolder_21.entry,
            flats_start=self.start_flat_url,
            flats_end=self.end_flat_url,
            darks_start=self.start_dark_url,
            extras={
                "darks_start": {"count_time": 0.3, "rotation_angle": 0.0},
                "flats_start": {"count_time": 0.3, "rotation_angle": 0.0},
                "flats_end": {"count_time": 0.3, "rotation_angle": 0.0},
            },
        )
        self.check_vds_from_file(
            file_=scan_subfolder_21.master_file, nx_entry=scan_subfolder_21.entry
        )

        # create a scan contained in subfolder221
        scan_subfolder_221 = self._simple_nx = MockNXtomo(
            scan_path=self.subsubfolder_221,
            n_proj=10,
            n_ini_proj=2,
            create_ini_dark=False,
            create_ini_flat=False,
            create_final_flat=False,
            dim=self.dim,
        ).scan
        # 2. create a second level of indirection for dark and flat and check
        # the VDS
        det_data_path = "/".join(
            (scan_subfolder_21.entry, "instrument", "detector", "data")
        )
        new_dark_url = DataUrl(
            file_path=scan_subfolder_21.master_file,
            data_path=det_data_path,
            data_slice=slice(0, 5),
            scheme="silx",
        )
        new_start_flat_url = DataUrl(
            file_path=scan_subfolder_21.master_file,
            data_path=det_data_path,
            data_slice=slice(5, 10),
            scheme="silx",
        )
        new_end_flat_url = DataUrl(
            file_path=scan_subfolder_21.master_file,
            data_path=det_data_path,
            data_slice=slice(12, 17),
            scheme="silx",
        )

        add_dark_flat_nx_file(
            file_path=scan_subfolder_221.master_file,
            entry=scan_subfolder_221.entry,
            flats_start=new_start_flat_url,
            flats_end=new_end_flat_url,
            darks_start=new_dark_url,
            extras={
                "darks_start": {"count_time": 0.3, "rotation_angle": 0.0},
                "flats_start": {"count_time": 0.3, "rotation_angle": 0.0},
                "flats_end": {"count_time": 0.3, "rotation_angle": 0.0},
            },
        )
        self.check_vds_from_file(
            file_=scan_subfolder_221.master_file, nx_entry=scan_subfolder_221.entry
        )

        # 3. move root folder and remove it to insure links are style valid
        shutil.move(src=self.folder_1, dst=self.mv_folder)
        shutil.move(src=self.folder_2, dst=self.mv_folder)
        new_scan_subfolder_221_m = scan_subfolder_221.master_file.replace(
            self.mv_folder, self.root_folder
        )

        self.check_vds_from_file(
            file_=new_scan_subfolder_221_m, nx_entry=scan_subfolder_221.entry
        )

    def check_vds_from_file(self, file_, nx_entry):
        with HDF5File(file_, mode="r", swmr=get_swmr_mode()) as h5s:
            entry_node = h5s[nx_entry]
            det_group = entry_node["instrument/detector"]
            det_data = det_group["data"]
            det_image_key = det_group["image_key"]

            # test dark
            numpy.testing.assert_array_equal(
                det_image_key[:5], [ImageKey.DARK_FIELD.value] * 5
            )
            numpy.testing.assert_array_equal(det_data[:5], self.start_dark)
            # test start flat
            numpy.testing.assert_array_equal(
                det_image_key[5:10], [ImageKey.FLAT_FIELD.value] * 5
            )
            numpy.testing.assert_array_equal(det_data[5:10], self.start_flat)
            # test end flat
            numpy.testing.assert_array_equal(
                det_image_key[-5:], [ImageKey.FLAT_FIELD.value] * 5
            )
            numpy.testing.assert_array_equal(det_data[-5:], self.end_flat)