test_hdf5converter.py 36.7 KB
Newer Older
payno's avatar
payno committed
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "09/10/2020"


import unittest
import shutil
import tempfile
import h5py
import numpy
import os
from nxtomomill import converter
38
39
from nxtomomill.converter.hdf5.acquisition.utils import get_nx_detectors
from nxtomomill.converter.hdf5.acquisition.utils import guess_nx_detector
40
41
from nxtomomill.converter.hdf5.acquisition.baseacquisition import EntryReader
from nxtomomill.converter.hdf5.acquisition.baseacquisition import DatasetReader
42
from nxtomomill.io.config import TomoHDF5Config
43
from tomoscan.esrf.hdf5scan import HDF5TomoScan
44
from tomoscan.validator import is_valid_for_reconstruction
45
from nxtomomill.test.utils.bliss import MockBlissAcquisition
46
from silx.io.url import DataUrl
47
from silx.io.utils import get_data
48
from glob import glob
49
from nxtomomill.io.framegroup import FrameGroup
payno's avatar
payno committed
50
from nxtomomill.utils import Format
51
import subprocess
payno's avatar
payno committed
52
53


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def url_has_been_copied(file_path: str, url: DataUrl):
    """util function to parse the `duplicate_data` folder and
    insure the copy of the dataset has been done"""
    duplicate_data_url = DataUrl(
        file_path=file_path, data_path="/duplicate_data", scheme="silx"
    )
    url_path = url.path()
    with EntryReader(duplicate_data_url) as duplicate_data_node:
        for _, dataset in duplicate_data_node.items():
            if "original_url" in dataset.attrs:
                original_url = dataset.attrs["original_url"]
                # the full dataset is registered in the attributes.
                # Here we only check the scan entry name
                if original_url.startswith(url_path):
                    return True
    return False


payno's avatar
payno committed
72
73
class TestH5ToNxConverter(unittest.TestCase):
    def setUp(self) -> None:
74
        super().setUp()
payno's avatar
payno committed
75
        self.folder = tempfile.mkdtemp()
76
        self.config = TomoHDF5Config()
payno's avatar
payno committed
77
78
79

    def tearDown(self) -> None:
        shutil.rmtree(self.folder)
80
        super().tearDown()
payno's avatar
payno committed
81
82

    def test_simple_converter_with_nx_detector_attr(self):
83
84
85
        """
        Test a simple conversion when NX_class is defined
        """
payno's avatar
payno committed
86
87
88
89
90
91
92
93
        bliss_mock = MockBlissAcquisition(
            n_sample=2,
            n_sequence=1,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
94
            detector_name="pcolinux",
payno's avatar
payno committed
95
96
97
        )
        for sample in bliss_mock.samples:
            self.assertTrue(os.path.exists(sample.sample_file))
98
99
            self.config.output_file = sample.sample_file.replace(".h5", ".nx")
            self.config.input_file = sample.sample_file
Henri Payno's avatar
Henri Payno committed
100
101
102
103
            assert (
                len(converter.get_bliss_tomo_entries(sample.sample_file, self.config))
                == 1
            )
104

105
            converter.from_h5_to_nx(
106
                configuration=self.config,
payno's avatar
payno committed
107
108
            )
            # insure only one file is generated
109
            self.assertTrue(os.path.exists(self.config.output_file))
payno's avatar
payno committed
110
            # insure data is here
111
            with h5py.File(self.config.output_file, mode="r") as h5s:
payno's avatar
payno committed
112
113
114
115
116
117
118
119
120
121
                for _, entry_node in h5s.items():
                    self.assertTrue("instrument/detector/data" in entry_node)
                    dataset = entry_node["instrument/detector/data"]
                # check virtual dataset are relative and valid
                self.assertTrue(dataset.is_virtual)
                for vs in dataset.virtual_sources():
                    self.assertFalse(os.path.isabs(vs.file_name))
                # insure connection is valid. There is no
                # 'VirtualSource.is_valid' like function
                self.assertFalse(dataset[()].min() == 0 and dataset[()].max() == 0)
122
123
                instrument_grp = entry_node.require_group("instrument")
                self.assertTrue("beam" in instrument_grp)
payno's avatar
payno committed
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
    def test_invalid_tomo_n(self):
        """Test translation fails if no detector can be found"""
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
        )
        self.assertTrue(len(bliss_mock.samples), 1)
        sample = bliss_mock.samples[0]
        self.assertTrue(os.path.exists(sample.sample_file))
        output_file = sample.sample_file.replace(".h5", ".nx")

        # rewrite tomo_n
        with h5py.File(sample.sample_file, mode="a") as h5s:
            for _, entry_node in h5s.items():
                if "technique/scan/tomo_n" in entry_node:
                    del entry_node["technique/scan/tomo_n"]
                    entry_node["technique/scan/tomo_n"] = 9999

        with self.assertRaises(ValueError):
149
150
151
152
153
            self.config.input_file = sample.sample_file
            self.config.output_file = output_file
            self.config.single_file = True
            self.config.no_input = True
            self.config.raises_error = True
154
            converter.from_h5_to_nx(configuration=self.config)
155

payno's avatar
payno committed
156
    def test_simple_converter_without_nx_detector_attr(self):
157
158
159
        """
        Test a simple conversion when no NX_class is defined
        """
payno's avatar
payno committed
160
161
162
163
164
165
166
167
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=3,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
168
            detector_name="tata_detector",
payno's avatar
payno committed
169
170
171
172
173
        )
        self.assertTrue(len(bliss_mock.samples), 1)
        sample = bliss_mock.samples[0]
        self.assertTrue(os.path.exists(sample.sample_file))
        output_file = sample.sample_file.replace(".h5", ".nx")
174
175
176
177
        self.config.input_file = sample.sample_file
        self.config.output_file = output_file
        self.config.single_file = True
        self.config.no_input = True
178
        converter.from_h5_to_nx(configuration=self.config)
payno's avatar
payno committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        # insure only one file is generated
        self.assertTrue(os.path.exists(output_file))
        # insure data is here
        with h5py.File(output_file, mode="r") as h5s:
            for _, entry_node in h5s.items():
                self.assertTrue("instrument/detector/data" in entry_node)
                dataset = entry_node["instrument/detector/data"]
            # check virtual dataset are relative and valid
            self.assertTrue(dataset.is_virtual)
            for vs in dataset.virtual_sources():
                self.assertFalse(os.path.isabs(vs.file_name))
            # insure connection is valid. There is no
            # 'VirtualSource.is_valid' like function
            self.assertFalse(dataset[()].min() == 0 and dataset[()].max() == 0)
193
194
195
196
197
198
199
200
            # check NXdata group
            self.assertTrue("data/data" in entry_node)
            self.assertFalse(
                entry_node["data/data"][()].min() == 0
                and entry_node["data/data"][()].max() == 0
            )
            self.assertTrue("data/rotation_angle" in entry_node)
            self.assertTrue("data/image_key" in entry_node)
payno's avatar
payno committed
201

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    def test_providing_existing_camera_name(self):
        """Test that detector can be provided to the h5_to_nx function and
        using linux wildcard"""
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=3,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="my_detector",
        )
        self.assertTrue(len(bliss_mock.samples), 1)
        sample = bliss_mock.samples[0]
        self.assertTrue(os.path.exists(sample.sample_file))
218
219
220
221
222
223
        self.config.output_file = sample.sample_file.replace(".h5", ".nx")
        self.config.valid_camera_names = ("my_detec*",)
        self.config.input_file = sample.sample_file
        self.config.single_file = True
        self.config.request_input = False
        self.config.raises_error = True
224
        self.config.rotation_angle_keys = ("hrsrot",)
225
        converter.from_h5_to_nx(configuration=self.config)
226
        # insure only one file is generated
227
        self.assertTrue(os.path.exists(self.config.output_file))
228
        # insure data is here
229
        with h5py.File(self.config.output_file, mode="r") as h5s:
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
            for _, entry_node in h5s.items():
                self.assertTrue("instrument/detector/data" in entry_node)
                dataset = entry_node["instrument/detector/data"]
            # check virtual dataset are relative and valid
            self.assertTrue(dataset.is_virtual)
            for vs in dataset.virtual_sources():
                self.assertFalse(os.path.isabs(vs.file_name))
            # insure connection is valid. There is no
            # 'VirtualSource.is_valid' like function
            self.assertFalse(dataset[()].min() == 0 and dataset[()].max() == 0)

    def test_providing_non_existing_camera_name(self):
        """Test translation fails if no detector can be found"""
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=3,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="toto_detector",
        )
        self.assertTrue(len(bliss_mock.samples), 1)
        sample = bliss_mock.samples[0]
        self.assertTrue(os.path.exists(sample.sample_file))
256
257
258
259
        self.config.input_file = sample.sample_file
        self.config.output_file = sample.sample_file.replace(".h5", ".nx")
        self.config.valid_camera_names = ("my_detec",)
        self.config.raises_error = True
260
        with self.assertRaises(ValueError):
261
            converter.from_h5_to_nx(configuration=self.config)
payno's avatar
payno committed
262

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    def test_z_series_conversion(self):
        """Test conversion of a zseries bliss (mock) acquisition"""
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=10,
            n_darks=5,
            n_flats=5,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="frelon1",
            acqui_type="zseries",
            z_values=(1, 2, 3),
        )
        self.assertTrue(len(bliss_mock.samples), 1)
        sample = bliss_mock.samples[0]
        self.assertTrue(os.path.exists(sample.sample_file))
280
281
        self.config.input_file = sample.sample_file
        self.config.output_file = sample.sample_file.replace(".h5", ".nx")
282
        res = converter.from_h5_to_nx(configuration=self.config)
283
284
285
286
287
        # insure the 4 files are generated: master file and one per z
        files = glob(os.path.dirname(sample.sample_file) + "/*.nx")
        self.assertEqual(len(files), 4)
        # try to create HDF5TomoScan from those to insure this is valid
        # and check z values for example
288
289
290
291
        for res_tuple in res:
            scan = HDF5TomoScan(scan=res_tuple[0], entry=res_tuple[1])
            if hasattr(scan, "z_translation"):
                self.assertTrue(scan.z_translation is not None)
292
            self.assertTrue(is_valid_for_reconstruction(scan))
293

294
295
296
297
    def test_ignore_sub_entries(self):
        """
        Test we can ignore some sub entries
        """
298
299
        from nxtomomill.test.utils.bliss import MockBlissAcquisition

300
301
302
303
304
305
306
307
308
309
310
311
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=10,
            n_darks=0,
            n_flats=0,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="pcolinux",
        )
        for sample in bliss_mock.samples:
            self.assertTrue(os.path.exists(sample.sample_file))
312
313
314
315
316
            self.config.output_file = sample.sample_file.replace(".h5", ".nx")
            self.config.input_file = sample.sample_file
            self.config.single_file = True
            self.config.sub_entries_to_ignore = ("6.1", "7.1")
            self.config.request_input = False
317
            converter.from_h5_to_nx(configuration=self.config)
318
            # insure only one file is generated
319
            self.assertTrue(os.path.exists(self.config.output_file))
320
            # insure data is here
321
            with h5py.File(self.config.output_file, mode="r") as h5s:
322
323
324
325
326
                for _, entry_node in h5s.items():
                    self.assertTrue("instrument/detector/data" in entry_node)
                    dataset = entry_node["instrument/detector/data"]
                # check virtual dataset are relative and valid
                self.assertTrue(dataset.is_virtual)
327
328
329
330
                self.assertEqual(
                    dataset.shape,
                    (10 * (10 - len(self.config.sub_entries_to_ignore)), 64, 64),
                )
331
332
333
334
335
336
                for vs in dataset.virtual_sources():
                    self.assertFalse(os.path.isabs(vs.file_name))
                # insure connection is valid. There is no
                # 'VirtualSource.is_valid' like function
                self.assertFalse(dataset[()].min() == 0 and dataset[()].max() == 0)

payno's avatar
payno committed
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

class TestDetectorDetection(unittest.TestCase):
    """
    Test functions to find nxdetector groups
    """

    def setUp(self) -> None:
        self.folder = tempfile.mkdtemp()

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

    @staticmethod
    def create_nx_detector(node: h5py.Group, name, with_nx_class):
        det_node = node.require_group(name)
        data = numpy.random.random(10 * 10 * 10).reshape(10, 10, 10)
        det_node["data"] = data
        if with_nx_class:
            if "NX_class" not in det_node.attrs:
                det_node.attrs["NX_class"] = "NXdetector"

    def test_get_nx_detectors(self):
        """test get_nx_detectors function"""
        h5file = os.path.join(self.folder, "h5file.hdf5")
        with h5py.File(h5file, mode="w") as h5s:
            self.create_nx_detector(node=h5s, name="det1", with_nx_class=True)
            self.create_nx_detector(node=h5s, name="det2", with_nx_class=False)
        with h5py.File(h5file, mode="r") as h5s:
365
            dets = get_nx_detectors(h5s)
payno's avatar
payno committed
366
367
            self.assertEqual(len(dets), 1)
            self.assertEqual(dets[0].name, "/det1")
368
            self.assertEqual(len(guess_nx_detector(h5s)), 2)
payno's avatar
payno committed
369
370
371
372
        with h5py.File(h5file, mode="a") as h5s:
            self.create_nx_detector(node=h5s, name="det3", with_nx_class=True)
            self.create_nx_detector(node=h5s, name="det4", with_nx_class=True)
        with h5py.File(h5file, mode="r") as h5s:
373
            dets = get_nx_detectors(h5s)
payno's avatar
payno committed
374
375
376
377
378
379
380
381
            self.assertEqual(len(dets), 3)

    def test_guess_nx_detector(self):
        """test guess_nx_detector function"""
        h5file = os.path.join(self.folder, "h5file.hdf5")
        with h5py.File(h5file, mode="w") as h5s:
            self.create_nx_detector(node=h5s, name="det2", with_nx_class=False)
        with h5py.File(h5file, mode="r") as h5s:
382
            dets = get_nx_detectors(h5s)
payno's avatar
payno committed
383
            self.assertEqual(len(dets), 0)
384
            dets = guess_nx_detector(h5s)
payno's avatar
payno committed
385
386
387
388
389
            self.assertEqual(dets[0].name, "/det2")
        with h5py.File(h5file, mode="w") as h5s:
            self.create_nx_detector(node=h5s, name="det3", with_nx_class=False)
            self.create_nx_detector(node=h5s, name="det4", with_nx_class=True)
        with h5py.File(h5file, mode="a") as h5s:
390
            dets = guess_nx_detector(h5s)
payno's avatar
payno committed
391
392
393
            self.assertEqual(len(dets), 2)


394
395
class TestXRDCTConversion(unittest.TestCase):
    def setUp(self) -> None:
396
        super().setUp()
397
        self.folder = tempfile.mkdtemp()
398
        self.config = TomoHDF5Config()
payno's avatar
payno committed
399
        self.config.format = Format.XRD_CT
400

payno's avatar
payno committed
401
402
    def tearDown(self) -> None:
        shutil.rmtree(self.folder)
403
        super().tearDown()
404
405
406
407
408

    def test_simple_converter_with_nx_detector_attr(self):
        """
        Test a simple conversion when NX_class is defined
        """
409
410
        from nxtomomill.test.utils.bliss import MockBlissAcquisition

411
412
413
414
415
416
417
418
419
420
421
422
423
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=10,
            n_darks=0,
            n_flats=0,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="pilatus",
            acqui_type="xrd-ct",
        )
        for sample in bliss_mock.samples:
            self.assertTrue(os.path.exists(sample.sample_file))
424
425
426
427
            self.config.input_file = sample.sample_file
            self.config.output_file = sample.sample_file.replace(".h5", ".nx")
            self.config.single_file = True
            self.config.request_input = False
428
            self.config.rotation_angle_keys = ("hrsrot",)
429
            converter.from_h5_to_nx(configuration=self.config)
430

431
            # insure only one file is generated
432
            self.assertTrue(os.path.exists(self.config.output_file))
433
            # insure data is here
434
            with h5py.File(self.config.output_file, mode="r") as h5s:
435
436
437
438
439
440
441
442
443
444
445
446
                for _, entry_node in h5s.items():
                    self.assertTrue("instrument/detector/data" in entry_node)
                    dataset = entry_node["instrument/detector/data"]
                # check virtual dataset are relative and valid
                self.assertTrue(dataset.is_virtual)
                for vs in dataset.virtual_sources():
                    self.assertFalse(os.path.isabs(vs.file_name))
                # insure connection is valid. There is no
                # 'VirtualSource.is_valid' like function
                self.assertFalse(dataset[()].min() == 0 and dataset[()].max() == 0)


447
class TestStandardAcqConversionWithExternalUrls(unittest.TestCase):
448
449
450
    """Test conversion when frames are provided from urls"""

    def setUp(self) -> None:
451
        super().setUp()
452
        self.folder = tempfile.mkdtemp()
453
        self.config = TomoHDF5Config()
454
        self.config.output_file = os.path.join(self.folder, "output.nx")
455
        self.config.rotation_angle_keys = ("hrsrot",)
456
457
458
459
460
461
462
463
464
465
466

    def create_scan(self, n_projection_scans, n_flats, n_darks, output_dir):
        """
        :param int n_projection_scans: number of scans beeing projections
        :param int n_flats: number of frame per flats
        :param int n_darks: number of frame per dark
        """
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=n_projection_scans,
467
468
            n_darks=n_darks,
            n_flats=n_flats,
469
470
471
            with_nx_detector_attr=True,
            output_dir=output_dir,
            detector_name="pcolinux",
Henri Payno's avatar
Henri Payno committed
472
            y_rot=True,
473
474
475
476
        )
        return bliss_mock.samples[0].sample_file

    def tearDown(self) -> None:
477
        shutil.rmtree(self.folder)
478
        super().tearDown()
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

    def test_dataset_1(self):
        """test a conversion where projections are contained in the
        input_file. Dark and flats are on a different file"""
        folder_1 = os.path.join(self.folder, "acqui_1")
        input_file = self.create_scan(
            n_projection_scans=6, n_flats=0, n_darks=0, output_dir=folder_1
        )
        folder_2 = os.path.join(self.folder, "acqui_2")
        dark_flat_file = self.create_scan(
            n_projection_scans=0, n_flats=1, n_darks=1, output_dir=folder_2
        )
        self.config.input_file = input_file

        # we want to take two scan of projections from the input file: 5.1
        # and 6.1. As the input file is provided we don't need to
        # specify it
        self.config.data_frame_grps = (
            FrameGroup(frame_type="proj", url=DataUrl(data_path="/5.1", scheme="silx")),
            FrameGroup(frame_type="proj", url=DataUrl(data_path="/6.1", scheme="silx")),
            FrameGroup(
                frame_type="flat",
                url=DataUrl(file_path=dark_flat_file, data_path="/2.1", scheme="silx"),
            ),
            FrameGroup(
                frame_type="dark",
                url=DataUrl(file_path=dark_flat_file, data_path="/3.1", scheme="silx"),
            ),
        )
508
        converter.from_h5_to_nx(
509
510
511
            configuration=self.config,
        )

512
513
514
        self.assertTrue(
            os.path.exists(self.config.output_file), "output file does not exists"
        )
515
516
517
518
519
520

        with h5py.File(self.config.output_file, mode="r") as h5s:
            self.assertEqual(len(h5s.items()), 1)
            self.assertTrue("entry0000" in h5s)

        scan = HDF5TomoScan(scan=self.config.output_file, entry="entry0000")
521
        self.assertTrue(is_valid_for_reconstruction(scan))
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543

        # check the `data`has been created
        self.assertTrue(len(scan.projections), 20)
        self.assertTrue(len(scan.darks), 10)
        # check data is a virtual dataset
        with h5py.File(self.config.output_file, mode="r") as h5f:
            dataset = h5f["entry0000/instrument/detector/data"]
            self.assertTrue(dataset.is_virtual)
        # check the `data` virtual dataset is valid
        # if the link fail then all values are zeros
        url = tuple(scan.projections.values())[0]
        proj_data = get_data(url)
        self.assertTrue(proj_data.min() != proj_data.max())

        url = tuple(scan.darks.values())[0]
        dark_data = get_data(url)
        self.assertTrue(dark_data.min() != dark_data.max())

        self.assertTrue(len(scan.flats), 10)
        url = tuple(scan.flats.values())[0]
        flat_data = get_data(url)
        self.assertTrue(flat_data.min() != flat_data.max())
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
    def test_dataset_2(self):
        """test a conversion where no input file is provided and
        where we have 2 projections in a file, 3 in an other.
        Flat and darks are also in another file. No flat provided.
        """
        folder_1 = os.path.join(self.folder, "acqui_1")
        file_1 = self.create_scan(
            n_projection_scans=6, n_flats=0, n_darks=0, output_dir=folder_1
        )
        folder_2 = os.path.join(self.folder, "acqui_2")
        file_2 = self.create_scan(
            n_projection_scans=6, n_flats=0, n_darks=0, output_dir=folder_2
        )
        folder_3 = os.path.join(self.folder, "acqui_3")
        file_3 = self.create_scan(
            n_projection_scans=0, n_flats=0, n_darks=1, output_dir=folder_3
        )
        folder_4 = os.path.join(self.folder, "acqui_4")
        file_4 = self.create_scan(
            n_projection_scans=0, n_flats=1, n_darks=0, output_dir=folder_4
        )

        # we want to take two scan of projections from the input file: 5.1
        # and 6.1. As the input file is provided we don't need to
        # specify it
570
571
        dark_url_1 = DataUrl(file_path=file_3, data_path="/2.1", scheme="silx")
        flat_url_1 = DataUrl(file_path=file_4, data_path="/2.1", scheme="silx")
572
573
574
575
        proj_url_1 = DataUrl(file_path=file_1, data_path="/5.1", scheme="silx")
        proj_url_2 = DataUrl(file_path=file_1, data_path="/6.1", scheme="silx")
        proj_url_3 = DataUrl(file_path=file_2, data_path="/4.1", scheme="silx")
        proj_url_4 = DataUrl(file_path=file_2, data_path="/2.1", scheme="silx")
576

577
        self.config.default_copy_behavior = True
578
579
580
        self.config.data_frame_grps = (
            FrameGroup(frame_type="dark", url=dark_url_1),
            FrameGroup(frame_type="flat", url=flat_url_1),
581
582
            FrameGroup(frame_type="proj", url=proj_url_1, copy=False),
            FrameGroup(frame_type="proj", url=proj_url_2, copy=False),
583
584
            FrameGroup(frame_type="proj", url=proj_url_3),
            FrameGroup(frame_type="proj", url=proj_url_4),
585
        )
586
587
        urls_copied = (dark_url_1, flat_url_1, proj_url_3, proj_url_4)
        urls_not_copied = (proj_url_1, proj_url_2)
588

589
        self.config.raises_error = True
590
        converter.from_h5_to_nx(
591
592
593
594
595
596
            configuration=self.config,
        )

        self.assertTrue(os.path.exists(self.config.output_file))

        with h5py.File(self.config.output_file, mode="r") as h5s:
597
            self.assertEqual(len(h5s.items()), 2)
598
            self.assertTrue("entry0000" in h5s)
599
            self.assertTrue("duplicate_data" in h5s)
600

601
602
603
604
605
606
607
608
609
610
611
612
613
614
        detector_url = DataUrl(
            file_path=self.config.output_file,
            data_path="/entry0000/instrument/detector/data",
            scheme="silx",
        )
        with DatasetReader(detector_url) as detector_dataset:
            self.assertTrue(detector_dataset.is_virtual)
            for i_vs, vs in enumerate(detector_dataset.virtual_sources()):
                self.assertFalse(os.path.isabs(vs.file_name))
                if i_vs in (0, 1, 4, 5):
                    self.assertEqual(vs.file_name, "output.nx")
                else:
                    self.assertEqual(vs.file_name, "acqui_1/sample_0/sample_0.h5")

615
        scan = HDF5TomoScan(scan=self.config.output_file, entry="entry0000")
616
        self.assertTrue(is_valid_for_reconstruction(scan))
617
618
619
620

        # check the `data`has been created
        self.assertTrue(len(scan.projections), 40)
        self.assertTrue(len(scan.darks), 10)
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
        # check the `data` virtual dataset is valid
        # if the link fail then all values are zeros
        url = tuple(scan.projections.values())[0]
        proj_data = get_data(url)
        self.assertTrue(proj_data.min() != proj_data.max())

        url = tuple(scan.darks.values())[0]
        dark_data = get_data(url)
        self.assertTrue(dark_data.min() != dark_data.max())

        self.assertTrue(len(scan.flats), 10)
        url = tuple(scan.flats.values())[0]
        flat_data = get_data(url)
        self.assertTrue(flat_data.min() != flat_data.max())

        with h5py.File(self.config.output_file, mode="r") as h5f:
            dataset = h5f["entry0000/instrument/detector/data"]
            self.assertTrue(dataset.shape, (60, 10, 10))
            with EntryReader(dark_url_1) as dark_entry:
                numpy.testing.assert_array_equal(
                    dark_entry["instrument/pcolinux/data"], dataset[0:10]
                )
            with EntryReader(flat_url_1) as flat_entry:
                numpy.testing.assert_array_equal(
                    flat_entry["instrument/pcolinux/data"], dataset[10:20]
                )
            with EntryReader(proj_url_1) as proj_entry_1:
                numpy.testing.assert_array_equal(
                    proj_entry_1["instrument/pcolinux/data"], dataset[20:30]
                )
            with EntryReader(proj_url_2) as proj_entry_2:
                numpy.testing.assert_array_equal(
                    proj_entry_2["instrument/pcolinux/data"], dataset[30:40]
                )
            with EntryReader(proj_url_3) as proj_entry_3:
                numpy.testing.assert_array_equal(
                    proj_entry_3["instrument/pcolinux/data"], dataset[40:50]
                )
            with EntryReader(proj_url_4) as proj_entry_4:
                numpy.testing.assert_array_equal(
                    proj_entry_4["instrument/pcolinux/data"], dataset[50:60]
                )
664
665
666

        for url in urls_copied:
            self.assertTrue(
667
                url_has_been_copied(file_path=self.config.output_file, url=url)
668
669
670
671
            )

        for url in urls_not_copied:
            self.assertFalse(
672
                url_has_been_copied(file_path=self.config.output_file, url=url)
673
            )
674

Henri Payno's avatar
Henri Payno committed
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
        # test with some extra parameters
        self.config.param_already_defined = {
            "x_pixel_size": 2.6 * 10e-6,
            "y_pixel_size": 2.7 * 10e-6,
            "energy": 12.2,
        }
        self.config.overwrite = True
        self.config.field_of_view = "Half"

        init_url_1 = DataUrl(file_path=file_1, data_path="/1.1", scheme="silx")

        self.config.default_copy_behavior = True
        self.config.data_frame_grps = (
            FrameGroup(frame_type="init", url=init_url_1),
            FrameGroup(frame_type="dark", url=dark_url_1),
            FrameGroup(frame_type="flat", url=flat_url_1),
            FrameGroup(frame_type="proj", url=proj_url_1, copy=False),
            FrameGroup(frame_type="proj", url=proj_url_2, copy=False),
            FrameGroup(frame_type="proj", url=proj_url_3),
            FrameGroup(frame_type="proj", url=proj_url_4),
        )

        converter.from_h5_to_nx(
            configuration=self.config,
        )
        scan.clear_caches()
        assert numpy.isclose(scan.energy, 12.2)
        assert numpy.isclose(scan.x_pixel_size, 2.6 * 10e-6)
        assert numpy.isclose(scan.y_pixel_size, 2.7 * 10e-6)
        with EntryReader(
            DataUrl(file_path=scan.master_file, data_path=scan.entry, scheme="h5py")
        ) as entry:
            assert "instrument/detector" in entry
            assert "instrument/detector/estimated_cor_from_motor" in entry

710

711
712
713
714
class TestZSeriesConversionWithExternalUrls(unittest.TestCase):
    """
    Test Zseries conversion from HDF5Config and providing urls
    """
715

716
    def setUp(self) -> None:
717
        super().setUp()
718
719
        self.folder = tempfile.mkdtemp()

720
        self.config = TomoHDF5Config()
721
722
        self.config.output_file = os.path.join(self.folder, "output.nx")

723
724
725
726
        camera_name = "frelon"
        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
727
            n_scan_per_sequence=2,
728
729
730
731
732
733
734
735
736
737
738
739
740
            n_darks=1,
            n_flats=0,
            with_nx_detector_attr=True,
            output_dir=os.path.join(self.folder, "seq_1"),
            detector_name=camera_name,
            acqui_type="zseries",
            z_values=(1, 2, 3),
        )
        self._zseries_1_file = bliss_mock.samples[0].sample_file

        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
741
            n_scan_per_sequence=2,
742
743
744
745
746
747
748
749
750
751
752
753
            n_darks=0,
            n_flats=1,
            with_nx_detector_attr=True,
            output_dir=os.path.join(self.folder, "seq_2"),
            detector_name=camera_name,
            acqui_type="zseries",
            z_values=(4, 5, 6),
        )
        self._zseries_2_file = bliss_mock.samples[0].sample_file

    def tearDown(self) -> None:
        shutil.rmtree(self.folder)
754
        super().tearDown()
755
756
757

    def test_dataset_zseries(self):
        """Test a zseries with only external scan entries"""
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

        # create the sequence to create: take two scan of two z (2, 3) from
        # the first sequence and two scan of one z from the second
        # sequence (z==4)
        dark_url_1 = DataUrl(
            file_path=self._zseries_1_file, data_path="/5.1", scheme="silx"
        )
        proj_url_1 = DataUrl(
            file_path=self._zseries_1_file, data_path="/6.1", scheme="silx"
        )
        proj_url_2 = DataUrl(
            file_path=self._zseries_1_file, data_path="/7.1", scheme="silx"
        )
        proj_url_3 = DataUrl(
            file_path=self._zseries_1_file, data_path="/9.1", scheme="silx"
        )
        proj_url_4 = DataUrl(
            file_path=self._zseries_1_file, data_path="/10.1", scheme="silx"
        )
        proj_url_5 = DataUrl(
            file_path=self._zseries_2_file, data_path="/3.1", scheme="silx"
        )
        proj_url_6 = DataUrl(
            file_path=self._zseries_2_file, data_path="/4.1", scheme="silx"
        )
        flat_url_1 = DataUrl(
            file_path=self._zseries_2_file, data_path="/2.1", scheme="silx"
        )
        self.config.default_copy_behavior = True
        self.config.single_file = True
        self.config.data_frame_grps = (
            FrameGroup(frame_type="dark", url=dark_url_1, copy=False),
            FrameGroup(frame_type="flat", url=flat_url_1, copy=False),
            FrameGroup(frame_type="proj", url=proj_url_1),
            FrameGroup(frame_type="proj", url=proj_url_2),
            FrameGroup(frame_type="proj", url=proj_url_3),
            FrameGroup(frame_type="proj", url=proj_url_4),
            FrameGroup(frame_type="proj", url=proj_url_5),
            FrameGroup(frame_type="proj", url=proj_url_6),
        )
        urls_copied = (
            proj_url_1,
            proj_url_2,
            proj_url_3,
            proj_url_4,
            proj_url_5,
            proj_url_6,
        )
        urls_not_copied = (flat_url_1, dark_url_1)

        # do conversion
        converter.from_h5_to_nx(
            configuration=self.config,
        )
        self.assertTrue(os.path.exists(self.config.output_file))
        with h5py.File(self.config.output_file, mode="r") as h5f:
            self.assertTrue("entry0000" in h5f)
            self.assertTrue("entry0001" in h5f)
            self.assertTrue("entry0002" in h5f)

        scan_z0 = HDF5TomoScan(scan=self.config.output_file, entry="entry0000")
        scan_z1 = HDF5TomoScan(scan=self.config.output_file, entry="entry0001")
        scan_z2 = HDF5TomoScan(scan=self.config.output_file, entry="entry0002")
        # check the `data`has been created
        self.assertTrue(len(scan_z0.projections), 40)
        self.assertTrue(len(scan_z1.projections), 40)
        self.assertTrue(len(scan_z2.projections), 40)

        for url in urls_copied:
            self.assertTrue(
                url_has_been_copied(file_path=self.config.output_file, url=url)
            )

        for url in urls_not_copied:
            self.assertFalse(
                url_has_been_copied(file_path=self.config.output_file, url=url)
            )

        # test a few slices
        with h5py.File(self.config.output_file, mode="r") as h5f:
            dataset = h5f["entry0000/instrument/detector/data"]
            self.assertTrue(dataset.shape, (60, 10, 10))

            with EntryReader(proj_url_1) as proj_entry_1:
                numpy.testing.assert_array_equal(
                    proj_entry_1["instrument/frelon/data"], dataset[10:20]
                )
            with EntryReader(proj_url_2) as proj_entry_2:
                numpy.testing.assert_array_equal(
                    proj_entry_2["instrument/frelon/data"], dataset[20:30]
                )
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


class TestH5ToNxFrmCommandLine(unittest.TestCase):
    """Test some call to the converter from the command line"""

    def setUp(self) -> None:
        self.cwd = os.getcwd()
        self.folder = tempfile.mkdtemp()

        bliss_mock = MockBlissAcquisition(
            n_sample=1,
            n_sequence=1,
            n_scan_per_sequence=2,
            n_darks=1,
            n_flats=1,
            with_nx_detector_attr=True,
            output_dir=self.folder,
            detector_name="pcolinux",
        )
        sample = bliss_mock.samples[0]
        self.input_file = sample.sample_file
        self.output_file = self.input_file.replace(".h5", ".nx")
        self.assertTrue(os.path.exists(self.input_file))

    def tearDown(self) -> None:
        os.chdir(self.cwd)
        shutil.rmtree(self.folder)

    def testDataDuplication(self):
        """test standard call h52nx but with '--data-copy' option"""
        # insure data is here
        os.chdir(os.path.dirname(self.input_file))
        input_file = os.path.basename(self.input_file)
        self.assertTrue(os.path.exists(input_file))
        output_file = os.path.basename(self.output_file)
        self.assertFalse(os.path.exists(output_file))
        cmd = " ".join(
            (
                "python",
                "-m",
                "nxtomomill",
                "h52nx",
                input_file,
                output_file,
                "--copy-data",
            )
        )
        subprocess.call(cmd, shell=True, cwd=os.path.dirname(self.input_file))

        self.assertTrue(os.path.exists(output_file))

        # insure all link are connected to one file: the internal one
        frame_dataset_url = DataUrl(
            file_path=output_file,
            data_path="/entry0000/instrument/detector/data",
            scheme="silx",
        )
        with DatasetReader(frame_dataset_url) as dataset:
            self.assertTrue(dataset.is_virtual)

            for vs_info in dataset.virtual_sources():
                self.assertTrue(dataset.is_virtual)
                self.assertEqual(os.path.realpath(vs_info.file_name), self.output_file)