-
Notifications
You must be signed in to change notification settings - Fork 29
/
conftest.py
1146 lines (960 loc) · 40.9 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019-2024 The kikuchipy developers
#
# This file is part of kikuchipy.
#
# kikuchipy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# kikuchipy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with kikuchipy. If not, see <http://www.gnu.org/licenses/>.
# Why is this file located in the top directory and not in tests/?
# Because if it was, running "pytest --doctest-modules src" wouldn't
# discover this file.
from io import TextIOWrapper
from numbers import Number
import os
from pathlib import Path
import tempfile
from typing import Callable, Generator
import dask.array as da
from diffpy.structure import Atom, Lattice, Structure
import h5py
import hyperspy.api as hs
import imageio.v3 as iio
import matplotlib.pyplot as plt
import numpy as np
from orix.crystal_map import CrystalMap, Phase, PhaseList, create_coordinate_arrays
from orix.quaternion import Rotation
import pytest
import skimage.color as skc
import kikuchipy as kp
from kikuchipy import constants
from kikuchipy.data._data import marshall
from kikuchipy.io.plugins._h5ebsd import _dict2hdf5group
if constants.installed["pyvista"]:
import pyvista as pv
pv.OFF_SCREEN = True
pv.global_theme.interactive = False
DATA_PATH = Path(__file__).parent / "src/kikuchipy/data"
# ------------------------------ Setup ------------------------------ #
def pytest_sessionstart(session):
_ = kp.data.nickel_ebsd_large(allow_download=True)
plt.rcParams["backend"] = "agg"
# ---------------------- pytest doctest-modules ---------------------- #
@pytest.fixture(autouse=True)
def doctest_setup_teardown(request):
# Temporarily turn off interactive plotting with Matplotlib
plt.ioff()
# Temporarily suppress HyperSpy's progressbar
hs.preferences.General.show_progressbar = False
# Temporary directory for saving files in
temporary_directory = tempfile.TemporaryDirectory()
original_directory = os.getcwd()
os.chdir(temporary_directory.name)
yield
# Teardown
os.chdir(original_directory)
@pytest.fixture(autouse=True)
def import_to_namespace(doctest_namespace) -> None:
doctest_namespace["DATA_PATH"] = DATA_PATH / "kikuchipy_h5ebsd"
# ----------------------------- Fixtures ----------------------------- #
@pytest.fixture
def assert_dictionary_func() -> Callable:
def assert_dictionary(dict1: dict, dict2: dict) -> None:
"""Assert that two dictionaries are (almost) equal.
Used to compare signal's axes managers or metadata in tests.
"""
for key in dict2.keys():
if isinstance(dict2[key], dict):
assert_dictionary(dict1[key], dict2[key])
else:
if isinstance(dict2[key], list) or isinstance(dict1[key], list):
dict2[key] = np.array(dict2[key])
dict1[key] = np.array(dict1[key])
if isinstance(dict2[key], (np.ndarray, Number)):
assert np.allclose(dict1[key], dict2[key])
else:
assert dict1[key] == dict2[key]
return assert_dictionary
@pytest.fixture
def dummy_signal(
dummy_background: np.ndarray,
) -> Generator[kp.signals.EBSD, None, None]:
"""Dummy signal of shape <3, 3|3, 3>. If this is changed, all
tests using this signal will fail since they compare the output from
methods using this signal (as input) to hard-coded outputs.
"""
nav_shape = (3, 3)
nav_size = int(np.prod(nav_shape))
sig_shape = (3, 3)
# fmt: off
dummy_array = np.array(
[
5, 6, 5, 7, 6, 5, 6, 1, 0, 9, 7, 8, 7, 0, 8, 8, 7, 6, 0, 3, 3, 5, 2,
9, 3, 3, 9, 8, 1, 7, 6, 4, 8, 8, 2, 2, 4, 0, 9, 0, 1, 0, 2, 2, 5, 8,
6, 0, 4, 7, 7, 7, 6, 0, 4, 1, 6, 3, 4, 0, 1, 1, 0, 5, 9, 8, 4, 6, 0,
2, 9, 2, 9, 4, 3, 6, 5, 6, 2, 5, 9
],
dtype=np.uint8
).reshape(nav_shape + sig_shape)
# fmt: on
# Initialize and set static background attribute
s = kp.signals.EBSD(dummy_array, static_background=dummy_background)
# Axes manager
s.axes_manager.navigation_axes[1].name = "x"
s.axes_manager.navigation_axes[0].name = "y"
# Crystal map
phase_list = PhaseList([Phase("a", space_group=225), Phase("b", space_group=227)])
y, x = np.indices(nav_shape)
s.xmap = CrystalMap(
rotations=Rotation.identity((nav_size,)),
# fmt: off
phase_id=np.array([
[0, 0, 1],
[1, 1, 0],
[0, 1, 0],
]).ravel(),
# fmt: on
phase_list=phase_list,
x=x.ravel(),
y=y.ravel(),
)
pc = np.arange(np.prod(nav_shape) * 3).reshape(nav_shape + (3,))
pc = pc.astype(float) / pc.max()
s.detector = kp.detectors.EBSDDetector(shape=sig_shape, pc=pc)
yield s
@pytest.fixture
def dummy_background() -> Generator[np.ndarray, None, None]:
"""Dummy static background image for the dummy signal. If this is
changed, all tests using this background will fail since they
compare the output from methods using this background (as input) to
hard-coded outputs.
"""
yield np.array([5, 4, 5, 4, 3, 4, 4, 4, 3], dtype=np.uint8).reshape((3, 3))
@pytest.fixture(params=[[(3, 3), (3, 3), False, np.float32]])
def ebsd_with_axes_and_random_data(request) -> Generator[kp.signals.EBSD, None, None]:
"""EBSD signal with minimally defined axes and random data.
Parameters expected in `request`
-------------------------------
navigation_shape : tuple
signal_shape : tuple
lazy : bool
dtype : numpy.dtype
"""
nav_shape, sig_shape, lazy, dtype = request.param
nav_ndim = len(nav_shape)
sig_ndim = len(sig_shape)
data_shape = nav_shape + sig_shape
data_size = int(np.prod(data_shape))
axes = []
if nav_ndim == 1:
axes.append({"name": "x", "size": nav_shape[0], "scale": 1})
if nav_ndim == 2:
axes.append({"name": "y", "size": nav_shape[0], "scale": 1})
axes.append({"name": "x", "size": nav_shape[1], "scale": 1})
if sig_ndim == 2:
axes.append({"name": "dy", "size": sig_shape[0], "scale": 1})
axes.append({"name": "dx", "size": sig_shape[1], "scale": 1})
if np.issubdtype(dtype, np.integer):
kw = {"low": 1, "high": 255, "size": data_size}
else:
kw = {"low": 0.1, "high": 1, "size": data_size}
if lazy:
data = da.random.uniform(**kw).reshape(data_shape).astype(dtype)
s = kp.signals.LazyEBSD(data, axes=axes)
else:
data = np.random.uniform(**kw).reshape(data_shape).astype(dtype)
s = kp.signals.EBSD(data, axes=axes)
yield s
@pytest.fixture
def nickel_structure() -> Generator[Structure, None, None]:
"""A diffpy.structure with a Nickel crystal structure."""
yield Structure(
atoms=[Atom("Ni", [0, 0, 0])],
lattice=Lattice(3.5236, 3.5236, 3.5236, 90, 90, 90),
)
@pytest.fixture
def nickel_phase(nickel_structure) -> Generator[Phase, None, None]:
yield Phase(name="ni", structure=nickel_structure, space_group=225)
@pytest.fixture
def pc1() -> Generator[list[float], None, None]:
"""One projection center (PC) in TSL convention."""
yield [0.4210, 0.7794, 0.5049]
@pytest.fixture(params=[[(1,), (60, 60)]])
def detector(request, pc1) -> Generator[kp.detectors.EBSDDetector, None, None]:
"""An EBSD detector of a given shape with a number of PCs given by
a navigation shape.
"""
nav_shape, sig_shape = request.param
yield kp.detectors.EBSDDetector(
shape=sig_shape,
binning=8,
px_size=70,
pc=np.ones(nav_shape + (3,)) * pc1,
sample_tilt=70,
tilt=0,
convention="tsl",
)
@pytest.fixture
def rotations() -> Generator[Rotation, None, None]:
yield Rotation([(2, 4, 6, 8), (-1, -3, -5, -7)])
@pytest.fixture
def get_single_phase_xmap(rotations) -> Generator[Callable, None, None]:
def _get_single_phase_xmap(
nav_shape,
rotations_per_point=5,
prop_names=("scores", "simulation_indices"),
name="a",
space_group=225,
phase_id=0,
step_sizes=None,
):
d, map_size = create_coordinate_arrays(shape=nav_shape, step_sizes=step_sizes)
rot_idx = np.random.choice(
np.arange(rotations.size), map_size * rotations_per_point
)
data_shape = (map_size,)
if rotations_per_point > 1:
data_shape += (rotations_per_point,)
d["rotations"] = rotations[rot_idx].reshape(*data_shape)
d["phase_id"] = np.ones(map_size) * phase_id
d["phase_list"] = PhaseList(Phase(name=name, space_group=space_group))
# Scores and simulation indices
d["prop"] = {
prop_names[0]: np.ones(data_shape, dtype=np.float32),
prop_names[1]: np.arange(np.prod(data_shape)).reshape(data_shape),
}
return CrystalMap(**d)
yield _get_single_phase_xmap
# ---------------------------- IO fixtures --------------------------- #
@pytest.fixture(params=["h5"])
def save_path_hdf5(request, tmpdir) -> Generator[Path, None, None]:
"""Temporary file in a temporary directory for use when tests need
to write, and sometimes read again, a signal to, and from, a file.
"""
ext = request.param
yield Path(tmpdir / f"patterns.{ext}")
@pytest.fixture()
def save_path_nordif(tmpdir) -> Generator[Path, None, None]:
yield Path(tmpdir / "nordif/save_temp.dat")
@pytest.fixture
def ni_small_axes_manager() -> Generator[dict, None, None]:
"""Axes manager for :func:`kikuchipy.data.nickel_ebsd_small`."""
names = ["y", "x", "dy", "dx"]
scales = [1.5, 1.5, 1, 1]
sizes = [3, 3, 60, 60]
navigates = [True, True, False, False]
axes_manager = {}
for i in range(len(names)):
axes_manager[f"axis-{i}"] = {
"_type": "UniformDataAxis",
"name": names[i],
"units": "um",
"navigate": navigates[i],
"is_binned": False,
"size": sizes[i],
"scale": scales[i],
"offset": 0.0,
}
yield axes_manager
@pytest.fixture(params=[("_x{}y{}.tif", (3, 3))])
def ebsd_directory(tmpdir, request) -> Generator[Path, None, None]:
"""Temporary directory with EBSD files as .tif, .png or .bmp files.
Parameters expected in `request`
-------------------------------
xy_pattern : str
nav_shape : tuple of ints
"""
s = kp.data.nickel_ebsd_small()
s.unfold_navigation_space()
xy_pattern, nav_shape = request.param
y, x = np.indices(nav_shape)
x = x.ravel()
y = y.ravel()
for i in range(s.axes_manager.navigation_size):
fname = str(tmpdir / ("pattern" + xy_pattern.format(x[i], y[i])))
iio.imwrite(fname, s.data[i])
yield tmpdir
# ------------------------ kikuchipy formats ------------------------- #
@pytest.fixture
def kikuchipy_h5ebsd_path() -> Generator[Path, None, None]:
yield DATA_PATH / "kikuchipy_h5ebsd"
@pytest.fixture
def nickel_ebsd_large_h5ebsd_renamed() -> Generator[Path, None, None]:
f1 = Path(marshall.path) / "data/nickel_ebsd_large/patterns.h5"
f2 = f1.rename(f1.with_suffix(".bak"))
yield f2
f2.rename(f1)
# --------------------------- EDAX formats --------------------------- #
@pytest.fixture
def edax_binary_path() -> Generator[Path, None, None]:
yield DATA_PATH / "edax_binary"
@pytest.fixture(params=[(1, (2, 3), (60, 60), "uint8", 2, False)])
def edax_binary_file(tmpdir, request) -> Generator[TextIOWrapper, None, None]:
"""Create a dummy EDAX binary UP1/2 file.
The creation of dummy UP1/2 files is explained in more detail in
kikuchipy/data/edax_binary/create_dummy_edax_binary_file.py.
Parameters expected in `request`
-------------------------------
up_version : int
navigation_shape : tuple of ints
signal_shape : tuple of ints
dtype : str
version : int
is_hex : bool
"""
# Unpack parameters
up_ver, (ny, nx), (sy, sx), dtype, ver, is_hex = request.param
if up_ver == 1:
fname = tmpdir.join("dummy_edax_file.up1")
f = open(fname, mode="w")
# File header: 16 bytes
# 4 bytes with the file version
np.array([ver], "uint32").tofile(f)
# 12 bytes with the pattern width, height and file offset position
np.array([sx, sy, 16], "uint32").tofile(f)
# Patterns
np.ones(ny * nx * sy * sx, dtype).tofile(f)
else: # up_ver == 2
fname = tmpdir.join("dummy_edax_file.up2")
f = open(fname, mode="w")
# File header: 42 bytes
# 4 bytes with the file version
np.array([ver], "uint32").tofile(f)
# 12 bytes with the pattern width, height and file offset position
np.array([sx, sy, 42], "uint32").tofile(f)
# 1 byte with any "extra patterns" (?)
np.array([1], "uint8").tofile(f)
# 8 bytes with the map width and height (same as square)
np.array([nx, ny], "uint32").tofile(f)
# 1 byte to say whether the grid is hexagonal
np.array([int(is_hex)], "uint8").tofile(f)
# 16 bytes with the horizontal and vertical step sizes
np.array([np.pi, np.pi / 2], "float64").tofile(f)
# Patterns
np.ones((ny * nx + ny // 2) * sy * sx, dtype).tofile(f)
f.close()
yield f
@pytest.fixture
def edax_h5ebsd_path() -> Generator[Path, None, None]:
yield DATA_PATH / "edax_h5ebsd"
# -------------------- Oxford Instruments formats -------------------- #
@pytest.fixture
def oxford_binary_path() -> Generator[Path, None, None]:
yield DATA_PATH / "oxford_binary"
@pytest.fixture
def oxford_h5ebsd_path() -> Generator[Path, None, None]:
yield DATA_PATH / "oxford_h5ebsd"
@pytest.fixture(params=[((2, 3), (60, 60), np.uint8, 2, False, True)])
def oxford_binary_file(tmpdir, request) -> Generator[TextIOWrapper, None, None]:
"""Create a dummy Oxford Instruments' binary .ebsp file.
The creation of a dummy .ebsp file is explained in more detail in
kikuchipy/data/oxford_binary/create_dummy_oxford_binary_file.py.
Parameters expected in `request`
-------------------------------
navigation_shape : tuple of ints
signal_shape : tuple of ints
dtype : numpy.dtype
version : int
compressed : bool
all_present : bool
"""
# Unpack parameters
(nr, nc), (sr, sc), dtype, ver, compressed, all_present = request.param
fname = tmpdir.join("dummy_oxford_file.ebsp")
f = open(fname, mode="w")
if ver > 0:
np.array(-ver, dtype=np.int64).tofile(f)
pattern_header_size = 16
if ver == 0:
pattern_footer_size = 0
elif ver == 1:
pattern_footer_size = 16
else:
pattern_footer_size = 18
n_patterns = nr * nc
n_pixels = sr * sc
if np.issubdtype(dtype, np.uint8):
n_bytes = n_pixels
else:
n_bytes = 2 * n_pixels
pattern_starts = np.arange(n_patterns, dtype=np.int64)
pattern_starts *= pattern_header_size + n_bytes + pattern_footer_size
pattern_starts += n_patterns * 8
if ver in [1, 2, 3]:
pattern_starts += 8
elif ver > 3:
np.array(0, dtype=np.uint8).tofile(f)
pattern_starts += 9
pattern_starts = np.roll(pattern_starts, shift=1)
if not all_present:
pattern_starts[0] = 0
pattern_starts.tofile(f)
new_order = np.roll(np.arange(n_patterns), shift=-1)
pattern_header = np.array([compressed, sr, sc, n_bytes], dtype=np.int32)
data = np.arange(n_patterns * n_pixels, dtype=dtype).reshape((nr, nc, sr, sc))
if not all_present:
new_order = new_order[1:]
for i in new_order:
r, c = np.unravel_index(i, (nr, nc))
pattern_header.tofile(f)
data[r, c].tofile(f)
if ver > 1:
np.array(1, dtype=bool).tofile(f) # has_beam_x
if ver > 0:
np.array(c, dtype=np.float64).tofile(f) # beam_x
if ver > 1:
np.array(1, dtype=bool).tofile(f) # has_beam_y
if ver > 0:
np.array(r, dtype=np.float64).tofile(f) # beam_y
f.close()
yield f
# -------------------------- EMsoft formats -------------------------- #
@pytest.fixture
def emsoft_ebsd_master_pattern_file() -> Generator[Path, None, None]:
yield DATA_PATH / "emsoft_ebsd_master_pattern/master_patterns.h5"
@pytest.fixture
def emsoft_ebsd_path() -> Generator[Path, None, None]:
yield DATA_PATH / "emsoft_ebsd"
@pytest.fixture
def emsoft_ebsd_file(emsoft_ebsd_path) -> Generator[Path, None, None]:
yield emsoft_ebsd_path / "EBSD_TEST_Ni.h5"
@pytest.fixture
def emsoft_ebsd_master_pattern_metadata() -> Generator[dict, None, None]:
fname = "master_patterns.h5"
yield {
"General": {"original_filename": fname, "title": fname.split(".")[0]},
"Signal": {"signal_type": "EBSDMasterPattern"},
}
@pytest.fixture(params=[["hemisphere", "energy", "height", "width"]])
def emsoft_ebsd_master_pattern_axes_manager(request) -> Generator[dict, None, None]:
axes = request.param
am = {
"hemisphere": {
"name": "hemisphere",
"scale": 1,
"offset": 0,
"size": 2,
"units": "",
"navigate": True,
},
"energy": {
"name": "energy",
"scale": 1,
"offset": 10.0,
"size": 11,
"units": "keV",
"navigate": True,
},
"height": {
"name": "height",
"scale": 1,
"offset": -7.0,
"size": 13,
"units": "px",
"navigate": False,
},
"width": {
"name": "width",
"scale": 1,
"offset": -7.0,
"size": 13,
"units": "px",
"navigate": False,
},
}
d = {}
for i, a in enumerate(axes):
d["axis-" + str(i)] = am[a]
yield d
@pytest.fixture
def emsoft_ecp_master_pattern_file(tmpdir) -> Generator[Path, None, None]:
"""Dummy EMsoft ECP master pattern file."""
fpath = tmpdir / "ecp_master_pattern.h5"
f = h5py.File(fpath, mode="w")
npx = 6
signal_shape = (npx * 2 + 1,) * 2
energies = np.linspace(10, 20, 11, dtype=np.float32)
data_shape = (len(energies),) + signal_shape
mp_lam_upper = np.ones((1,) + data_shape, dtype=np.float32) * energies.reshape(
(1, 11, 1, 1)
)
mp_lam_lower = mp_lam_upper
circle = kp.filters.Window(shape=signal_shape).astype(np.float32)
mp_sph_upper = mp_lam_upper.squeeze() * circle
mp_sph_lower = mp_sph_upper
data = {
"CrystalData": {
"AtomData": np.array(
[[0.1587, 0], [0.6587, 0], [0, 0.25], [1, 1], [0.005, 0.005]],
dtype=np.float32,
),
"Atomtypes": np.array([13, 29], dtype=np.int32),
"CrystalSystem": 2,
"LatticeParameters": np.array([0.5949, 0.5949, 0.5821, 90, 90, 90]),
"Natomtypes": 2,
"Source": "Su Y.C., Yan J., Lu P.T., Su J.T.: Thermodynamic...",
"SpaceGroupNumber": 140,
"SpaceGroupSetting": 1,
},
"EMData": {
"ECPmaster": {
"EkeV": np.linspace(10, 20, 11, dtype=np.float32),
"mLPNH": mp_lam_upper, # mLPSH written below
"masterSPNH": mp_sph_upper,
"masterSPSH": mp_sph_lower,
"numset": 1,
}
},
"NMLparameters": {
"ECPMasterNameList": {"dmin": 0.05, "npx": npx},
"MCCLNameList": {
"Ebinsize": energies[1] - energies[0],
"Ehistmin": np.min(energies),
"EkeV": np.max(energies),
"MCmode": "CSDA",
"dataname": "crystal_data/al2cu/al2cu_mc_mp_20kv.h5",
"depthmax": 100.0,
"depthstep": 1.0,
"mode": "bse1",
"numsx": npx,
"sigend": 10.0,
"sigstart": 0.0,
"sigstep": 2.0,
"totnum_el": 2000000000,
},
"BetheList": {"c1": 4.0, "c2": 8.0, "c3": 50.0, "sgdbdiff": 1.0},
},
"EMheader": {
"ECPmaster": {"ProgramName": np.array([b"EMECPmaster.f90"], dtype="S15")},
},
}
_dict2hdf5group(dictionary=data, group=f["/"])
# One chunked data set
f["EMData/ECPmaster"].create_dataset("mLPSH", data=mp_lam_lower, chunks=True)
# One byte string with latin-1 stuff
creation_time = b"12:30:13.559 PM\xf0\x14\x1e\xc8\xbcU"
f["CrystalData"].create_dataset("CreationTime", data=creation_time)
f.close()
yield fpath
@pytest.fixture
def emsoft_tkd_master_pattern_file(tmpdir) -> Generator[Path, None, None]:
fpath = tmpdir / "tkd_master_pattern.h5"
f = h5py.File(fpath, mode="w")
npx = 6
signal_shape = (npx * 2 + 1,) * 2
energies = np.linspace(10, 20, 11, dtype=np.float32)
data_shape = (len(energies),) + signal_shape
mp_lam_upper = np.ones((1,) + data_shape, dtype=np.float32) * energies.reshape(
(1, 11, 1, 1)
)
mp_lam_lower = mp_lam_upper
circle = kp.filters.Window(shape=signal_shape).astype(np.float32)
mp_sph_upper = mp_lam_upper.squeeze() * circle
mp_sph_lower = mp_sph_upper
data = {
"CrystalData": {
"AtomData": np.array(
[[0.1587, 0], [0.6587, 0], [0, 0.25], [1, 1], [0.005, 0.005]],
dtype=np.float32,
),
"Atomtypes": np.array([13, 29], dtype=np.int32),
"CrystalSystem": 2,
"LatticeParameters": np.array([0.5949, 0.5949, 0.5821, 90, 90, 90]),
"Natomtypes": 2,
"Source": "Su Y.C., Yan J., Lu P.T., Su J.T.: Thermodynamic...",
"SpaceGroupNumber": 140,
"SpaceGroupSetting": 1,
},
"EMData": {
"TKDmaster": {
"BetheParameters": np.array([4, 8, 50, 1], dtype=np.float32),
"EkeVs": np.linspace(10, 20, 11, dtype=np.float32),
"mLPNH": mp_lam_upper,
"masterSPNH": mp_sph_upper,
"masterSPSH": mp_sph_lower,
"numEbins": len(energies),
"numset": 1,
}
},
"NMLparameters": {
"TKDMasterNameList": {"dmin": 0.05, "npx": npx},
"MCCLfoilNameList": {
"Ebinsize": energies[1] - energies[0],
"Ehistmin": np.min(energies),
"EkeV": np.max(energies),
"MCmode": "CSDA",
"dataname": "crystal_data/al2cu/al2cu_mc_mp_20kv.h5",
"depthmax": 100.0,
"depthstep": 1.0,
"numsx": npx,
"sig": -20.0,
"totnum_el": 2000000000,
},
"BetheList": {"c1": 4.0, "c2": 8.0, "c3": 50.0, "sgdbdiff": 1.0},
},
"EMheader": {
"TKDmaster": {"ProgramName": np.array([b"EMTKDmaster.f90"], dtype="S15")},
},
}
_dict2hdf5group(dictionary=data, group=f["/"])
# One chunked data set
f["EMData/TKDmaster"].create_dataset("mLPSH", data=mp_lam_lower, chunks=True)
# One byte string with latin-1 stuff
creation_time = b"12:30:13.559 PM\xf0\x14\x1e\xc8\xbcU"
f["CrystalData"].create_dataset("CreationTime", data=creation_time)
f.close()
yield fpath
# -------------------------- NORDIF formats -------------------------- #
@pytest.fixture
def nordif_path() -> Generator[Path, None, None]:
yield DATA_PATH / "nordif"
@pytest.fixture
def nordif_renamed_calibration_pattern(
nordif_path: Path,
) -> Generator[Path, None, None]:
fname = "Background calibration pattern.bmp"
f1 = nordif_path / fname
f2 = f1.rename(f1.with_suffix(".bak"))
yield f2
f2.rename(f1)
# -------------------------- Bruker formats -------------------------- #
@pytest.fixture
def bruker_path() -> Generator[Path, None, None]:
yield DATA_PATH / "bruker_h5ebsd"
@pytest.fixture
def bruker_h5ebsd_file(tmpdir) -> Generator[Path, None, None]:
"""Bruker h5ebsd file with no region of interest."""
s = kp.data.nickel_ebsd_small()
ny, nx = s._navigation_shape_rc
n = ny * nx
sy, sx = s._signal_shape_rc
fpath = tmpdir / "patterns.h5"
f = h5py.File(fpath, mode="w")
# Top group
man = f.create_dataset("Manufacturer", shape=(1,), dtype="|S11")
man[()] = b"Bruker Nano"
ver = f.create_dataset("Version", shape=(1,), dtype="|S10")
ver[()] = b"Esprit 2.X"
scan = f.create_group("Scan 0")
# EBSD
ebsd = scan.create_group("EBSD")
ones9 = np.ones(n, dtype=np.float32)
zeros9 = np.zeros(n, dtype=np.float32)
ebsd_data = ebsd.create_group("Data")
ebsd_data.create_dataset("DD", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("MAD", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("MADPhase", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("NIndexedBands", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PCX", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PCY", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PHI", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Phase", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("RadonBandCount", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("RadonQuality", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("RawPatterns", data=s.data.reshape((n, sy, sx)))
ebsd_data.create_dataset("X BEAM", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("X SAMPLE", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Y BEAM", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("Y SAMPLE", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Z SAMPLE", dtype=np.float32, data=zeros9)
ebsd_data.create_dataset("phi1", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("phi2", dtype=np.float32, data=ones9)
ebsd_header = ebsd.create_group("Header")
ebsd_header.create_dataset("CameraTilt", dtype=float, data=0)
ebsd_header.create_dataset("DetectorFullHeightMicrons", dtype=np.int32, data=sy)
ebsd_header.create_dataset("DetectorFullWidthMicrons", dtype=np.int32, data=sx)
grid_type = ebsd_header.create_dataset("Grid Type", shape=(1,), dtype="|S9")
grid_type[()] = b"isometric"
ebsd_header.create_dataset("KV", dtype=float, data=20)
ebsd_header.create_dataset("MADMax", dtype=float, data=1.5)
ebsd_header.create_dataset("Magnification", dtype=float, data=200)
ebsd_header.create_dataset("MapStepFactor", dtype=float, data=4)
ebsd_header.create_dataset("MaxRadonBandCount", dtype=np.int32, data=11)
ebsd_header.create_dataset("MinIndexedBands", dtype=np.int32, data=5)
ebsd_header.create_dataset("NCOLS", dtype=np.int32, data=nx)
ebsd_header.create_dataset("NROWS", dtype=np.int32, data=ny)
ebsd_header.create_dataset("NPoints", dtype=np.int32, data=n)
original_file = ebsd_header.create_dataset("OriginalFile", shape=(1,), dtype="|S50")
original_file[()] = b"/a/home/for/your/data.h5"
ebsd_header.create_dataset("PatternHeight", dtype=np.int32, data=sy)
ebsd_header.create_dataset("PatternWidth", dtype=np.int32, data=sx)
ebsd_header.create_dataset("PixelByteCount", dtype=np.int32, data=1)
s_mean = s.nanmean((2, 3)).data.astype(np.uint8)
ebsd_header.create_dataset("SEM Image", data=skc.gray2rgb(s_mean))
ebsd_header.create_dataset("SEPixelSizeX", dtype=float, data=1)
ebsd_header.create_dataset("SEPixelSizeY", dtype=float, data=1)
ebsd_header.create_dataset("SampleTilt", dtype=float, data=70)
bg = s.static_background
ebsd_header.create_dataset("StaticBackground", dtype=np.uint16, data=bg)
ebsd_header.create_dataset("TopClip", dtype=float, data=1)
ebsd_header.create_dataset("UnClippedPatternHeight", dtype=np.int32, data=sy)
ebsd_header.create_dataset("WD", dtype=float, data=1)
ebsd_header.create_dataset("XSTEP", dtype=float, data=1.5)
ebsd_header.create_dataset("YSTEP", dtype=float, data=1.5)
ebsd_header.create_dataset("ZOffset", dtype=float, data=0)
phase = ebsd_header.create_group("Phases/1")
formula = phase.create_dataset("Formula", shape=(1,), dtype="|S2")
formula[()] = b"Ni"
phase.create_dataset("IT", dtype=np.int32, data=225)
phase.create_dataset(
"LatticeConstants",
dtype=np.float32,
data=np.array([3.56, 3.56, 3.56, 90, 90, 90]),
)
name = phase.create_dataset("Name", shape=(1,), dtype="|S6")
name[()] = b"Nickel"
phase.create_dataset("Setting", dtype=np.int32, data=1)
space_group = phase.create_dataset("SpaceGroup", shape=(1,), dtype="|S5")
space_group[()] = b"Fm-3m"
atom_pos = phase.create_group("AtomPositions")
atom_pos1 = atom_pos.create_dataset("1", shape=(1,), dtype="|S17")
atom_pos1[()] = b"Ni,0,0,0,1,0.0035"
# SEM
sem = scan.create_group("SEM")
sem.create_dataset("SEM IX", dtype=np.int32, data=np.ones(1))
sem.create_dataset("SEM IY", dtype=np.int32, data=np.ones(1))
sem.create_dataset("SEM Image", data=skc.gray2rgb(s_mean))
sem.create_dataset("SEM ImageHeight", dtype=np.int32, data=3)
sem.create_dataset("SEM ImageWidth", dtype=np.int32, data=3)
sem.create_dataset("SEM KV", dtype=float, data=20)
sem.create_dataset("SEM Magnification", dtype=float, data=200)
sem.create_dataset("SEM WD", dtype=float, data=24.5)
sem.create_dataset("SEM XResolution", dtype=float, data=1)
sem.create_dataset("SEM YResolution", dtype=float, data=1)
sem.create_dataset("SEM ZOffset", dtype=float, data=0)
f.close()
yield fpath
@pytest.fixture
def bruker_h5ebsd_roi_file(tmpdir) -> Generator[Path, None, None]:
"""Bruker h5ebsd file with rectangular region of interest (and SEM
group under EBSD group).
"""
s = kp.data.nickel_ebsd_small()
ny, nx = s._navigation_shape_rc
n = ny * nx
sy, sx = s._signal_shape_rc
fpath = tmpdir / "patterns_roi.h5"
f = h5py.File(fpath, mode="w")
# Top group
man = f.create_dataset("Manufacturer", shape=(1,), dtype="|S11")
man[()] = b"Bruker Nano"
ver = f.create_dataset("Version", shape=(1,), dtype="|S10")
ver[()] = b"Esprit 2.X"
scan = f.create_group("Scan 0")
# EBSD
ebsd = scan.create_group("EBSD")
# ROI and shape
roi = np.array(
[
[0, 1, 1], # 0, 1, 2 | (0, 0) (0, 1) (0, 2)
[0, 1, 1], # 3, 4, 5 | (1, 0) (1, 1) (1, 2)
[0, 1, 1], # 6, 7, 8 | (2, 0) (2, 1) (2, 2)
],
dtype=bool,
).flatten()
# Order of ROI patterns: 4, 1, 2, 5, 7, 8
iy = np.array([1, 0, 0, 1, 2, 2], dtype=int)
ix = np.array([1, 1, 2, 2, 1, 2], dtype=int)
# Data
ones9 = np.ones(9, dtype=np.float32)[roi]
zeros9 = np.zeros(9, dtype=np.float32)[roi]
ebsd_data = ebsd.create_group("Data")
ebsd_data.create_dataset("DD", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("MAD", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("MADPhase", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("NIndexedBands", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PCX", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PCY", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("PHI", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Phase", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("RadonBandCount", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("RadonQuality", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("RawPatterns", data=s.data.reshape((n, sy, sx))[roi])
ebsd_data.create_dataset("X BEAM", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("X SAMPLE", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Y BEAM", dtype=np.int32, data=ones9)
ebsd_data.create_dataset("Y SAMPLE", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("Z SAMPLE", dtype=np.float32, data=zeros9)
ebsd_data.create_dataset("phi1", dtype=np.float32, data=ones9)
ebsd_data.create_dataset("phi2", dtype=np.float32, data=ones9)
# Header
ebsd_header = ebsd.create_group("Header")
ebsd_header.create_dataset("CameraTilt", dtype=float, data=0)
ebsd_header.create_dataset("DetectorFullHeightMicrons", dtype=np.int32, data=23700)
ebsd_header.create_dataset("DetectorFullWidthMicrons", dtype=np.int32, data=31600)
grid_type = ebsd_header.create_dataset("Grid Type", shape=(1,), dtype="|S9")
grid_type[()] = b"isometric"
ebsd_header.create_dataset("KV", dtype=float, data=20)
ebsd_header.create_dataset("MADMax", dtype=float, data=1.5)
ebsd_header.create_dataset("Magnification", dtype=float, data=200)
ebsd_header.create_dataset("MapStepFactor", dtype=float, data=4)
ebsd_header.create_dataset("MaxRadonBandCount", dtype=np.int32, data=11)
ebsd_header.create_dataset("MinIndexedBands", dtype=np.int32, data=5)
ebsd_header.create_dataset("NCOLS", dtype=np.int32, data=nx)
ebsd_header.create_dataset("NROWS", dtype=np.int32, data=ny)
ebsd_header.create_dataset("NPoints", dtype=np.int32, data=n)
original_file = ebsd_header.create_dataset("OriginalFile", shape=(1,), dtype="|S50")
original_file[()] = b"/a/home/for/your/data.h5"
ebsd_header.create_dataset("PatternHeight", dtype=np.int32, data=sy)
ebsd_header.create_dataset("PatternWidth", dtype=np.int32, data=sx)
ebsd_header.create_dataset("PixelByteCount", dtype=np.int32, data=1)
s_mean = s.nanmean((2, 3)).data.astype(np.uint8)
ebsd_header.create_dataset("SEM Image", data=skc.gray2rgb(s_mean))
ebsd_header.create_dataset("SEPixelSizeX", dtype=float, data=1)
ebsd_header.create_dataset("SEPixelSizeY", dtype=float, data=1)
ebsd_header.create_dataset("SampleTilt", dtype=float, data=70)
ebsd_header.create_dataset(
"StaticBackground", dtype=np.uint16, data=s.static_background
)
ebsd_header.create_dataset("TopClip", dtype=float, data=1)
ebsd_header.create_dataset("UnClippedPatternHeight", dtype=np.int32, data=sy)
ebsd_header.create_dataset("WD", dtype=float, data=1)
ebsd_header.create_dataset("XSTEP", dtype=float, data=1.5)
ebsd_header.create_dataset("YSTEP", dtype=float, data=1.5)
ebsd_header.create_dataset("ZOffset", dtype=float, data=0)
# Phases
phase = ebsd_header.create_group("Phases/1")
formula = phase.create_dataset("Formula", shape=(1,), dtype="|S2")
formula[()] = b"Ni"
phase.create_dataset("IT", dtype=np.int32, data=225)
phase.create_dataset(