ePDFsuite 0.1.4__tar.gz → 0.1.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/PKG-INFO +2 -1
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/pyproject.toml +2 -1
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/PKG-INFO +2 -1
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/requires.txt +1 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/ePDFsuite.py +133 -37
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/filereader.py +94 -32
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/recalibration.py +179 -13
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/README.md +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/setup.cfg +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/setup.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/SOURCES.txt +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/dependency_links.txt +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/entry_points.txt +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/ePDFsuite.egg-info/top_level.txt +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/PDF_BatchAnalysis.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/__init__.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/_launcher.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/app_epdfsuite.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/calibration.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/camera_library.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/lobato_scattering.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/pdf_extraction.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/snr.py +0 -0
- {epdfsuite-0.1.4 → epdfsuite-0.1.7}/src/epdfsuite/utilities.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ePDFsuite
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.7
|
|
4
4
|
Summary: Python toolkit for electron pair distribution function (ePDF) analysis from SAED data
|
|
5
5
|
Author: Nicolas Ratel-Ramond
|
|
6
6
|
License: MIT
|
|
@@ -28,6 +28,7 @@ Requires-Dist: pymatgen>=2024.1.1
|
|
|
28
28
|
Requires-Dist: hyperspy<3.0.0,>=2.0.0
|
|
29
29
|
Requires-Dist: pyFAI>=2024.0.0
|
|
30
30
|
Requires-Dist: scikit-image<1.0.0,>=0.22.0
|
|
31
|
+
Requires-Dist: ediff>=1.0
|
|
31
32
|
Requires-Dist: ipywidgets>=8.0.0
|
|
32
33
|
Requires-Dist: ipykernel>=6.0.0
|
|
33
34
|
Requires-Dist: plotly>=5.0.0
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "ePDFsuite"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.7"
|
|
8
8
|
description = "Python toolkit for electron pair distribution function (ePDF) analysis from SAED data"
|
|
9
9
|
authors = [{name = "Nicolas Ratel-Ramond"}]
|
|
10
10
|
readme = "README.md"
|
|
@@ -34,6 +34,7 @@ dependencies = [
|
|
|
34
34
|
"hyperspy>=2.0.0,<3.0.0",
|
|
35
35
|
"pyFAI>=2024.0.0",
|
|
36
36
|
"scikit-image>=0.22.0,<1.0.0",
|
|
37
|
+
"ediff>=1.0",
|
|
37
38
|
"ipywidgets>=8.0.0",
|
|
38
39
|
"ipykernel>=6.0.0",
|
|
39
40
|
"plotly>=5.0.0",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ePDFsuite
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.7
|
|
4
4
|
Summary: Python toolkit for electron pair distribution function (ePDF) analysis from SAED data
|
|
5
5
|
Author: Nicolas Ratel-Ramond
|
|
6
6
|
License: MIT
|
|
@@ -28,6 +28,7 @@ Requires-Dist: pymatgen>=2024.1.1
|
|
|
28
28
|
Requires-Dist: hyperspy<3.0.0,>=2.0.0
|
|
29
29
|
Requires-Dist: pyFAI>=2024.0.0
|
|
30
30
|
Requires-Dist: scikit-image<1.0.0,>=0.22.0
|
|
31
|
+
Requires-Dist: ediff>=1.0
|
|
31
32
|
Requires-Dist: ipywidgets>=8.0.0
|
|
32
33
|
Requires-Dist: ipykernel>=6.0.0
|
|
33
34
|
Requires-Dist: plotly>=5.0.0
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from .filereader import load_data
|
|
2
|
-
from .recalibration import recalibrate_from_isocurve
|
|
2
|
+
from .recalibration import recalibrate_from_isocurve, center_calc_ediff
|
|
3
3
|
from .pdf_extraction import compute_ePDF
|
|
4
4
|
from pyFAI import load
|
|
5
5
|
import fabio
|
|
@@ -28,7 +28,14 @@ class SAEDProcessor:
|
|
|
28
28
|
mtf_file=None,
|
|
29
29
|
wiener_epsilon=None,
|
|
30
30
|
dqe_file=None,
|
|
31
|
-
verbose=False
|
|
31
|
+
verbose=False,
|
|
32
|
+
# instrument parameters
|
|
33
|
+
precession_angle=None,
|
|
34
|
+
initial_center=None,
|
|
35
|
+
# processing parameters
|
|
36
|
+
skip_center_recalibration=False,
|
|
37
|
+
amorphous=False
|
|
38
|
+
):
|
|
32
39
|
"""
|
|
33
40
|
Initialise a SAED data processor.
|
|
34
41
|
|
|
@@ -57,7 +64,20 @@ class SAEDProcessor:
|
|
|
57
64
|
If ``None``, Wiener deconvolution if MTF is available, else no deconvolution
|
|
58
65
|
verbose : bool, optional
|
|
59
66
|
If ``True``, print metadata and detector info. Default is ``False``.
|
|
67
|
+
precession_angle : float, optional
|
|
68
|
+
The precession angle of the electron beam in degrees. If ``None``, the angle is not used.
|
|
69
|
+
amorphous : bool, optional, default=True
|
|
70
|
+
Selects the automatic beam-centre detection method:
|
|
71
|
+
- ``True`` : :func:`recalibrate_from_isocurve` (iso-intensity
|
|
72
|
+
contours), suited to amorphous / diffuse-scattering halos
|
|
73
|
+
(no sharp ring edge required).
|
|
74
|
+
- ``False`` : :func:`center_calc_ediff` (Hough transform),
|
|
75
|
+
suited to crystalline patterns with well-defined diffraction
|
|
76
|
+
rings/spots.
|
|
77
|
+
In both cases, falls back to the intensity maximum if the
|
|
78
|
+
selected method fails.
|
|
60
79
|
"""
|
|
80
|
+
self.amorphous = amorphous
|
|
61
81
|
self.dm4_file = image_file
|
|
62
82
|
self.poni_file = poni_file
|
|
63
83
|
metadata, img = load_data(image_file, verbose=verbose)
|
|
@@ -100,22 +120,43 @@ class SAEDProcessor:
|
|
|
100
120
|
else:
|
|
101
121
|
self.ismtf = False
|
|
102
122
|
|
|
103
|
-
# Determine beam centre automatically
|
|
104
|
-
#
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
123
|
+
# Determine beam centre automatically.
|
|
124
|
+
# amorphous=True -> iso-intensity contour method (amorphous halos)
|
|
125
|
+
# amorphous=False -> ediff Hough-based detection (crystalline rings)
|
|
126
|
+
# Fall back to the intensity-maximum if the selected method fails.
|
|
127
|
+
if not skip_center_recalibration:
|
|
128
|
+
try:
|
|
129
|
+
if self.amorphous:
|
|
130
|
+
cx, cy = recalibrate_from_isocurve(
|
|
131
|
+
self.img, mask=_mask_as_array(self.mask), plot=False,
|
|
132
|
+
initial_center=initial_center
|
|
133
|
+
)
|
|
134
|
+
print(f'Centre estimate from iso-intensity contours: (x={cx:.2f}, y={cy:.2f})')
|
|
135
|
+
else:
|
|
136
|
+
cx, cy = center_calc_ediff(self.img)
|
|
137
|
+
print(f'Centre estimate from ediff (Hough): (x={cx:.2f}, y={cy:.2f})')
|
|
138
|
+
except Exception as _e:
|
|
139
|
+
_yx = np.unravel_index(np.argmax(self.img), self.img.shape)
|
|
140
|
+
cy, cx = float(_yx[0]), float(_yx[1])
|
|
141
|
+
print(
|
|
142
|
+
f'Warning: centre detection failed ({_e}). '
|
|
143
|
+
f'Falling back to intensity maximum: (x={cx:.1f}, y={cy:.1f}). '
|
|
144
|
+
'Refine manually in the app.'
|
|
145
|
+
)
|
|
146
|
+
self.center = (cx, cy)
|
|
147
|
+
else:
|
|
148
|
+
if initial_center is not None:
|
|
149
|
+
self.center = initial_center
|
|
150
|
+
print(f'Using user-supplied initial center: (x={self.center[0]:.2f}, y={self.center[1]:.2f})')
|
|
151
|
+
else:
|
|
152
|
+
_yx = np.unravel_index(np.argmax(self.img), self.img.shape)
|
|
153
|
+
cy, cx = float(_yx[0]), float(_yx[1])
|
|
154
|
+
self.center = (cx, cy)
|
|
155
|
+
print(f'No initial center provided. Using intensity maximum: (x={cx:.1f}, y={cy:.1f}).')
|
|
156
|
+
# Manage precession angle: if 0, set to None to avoid unnecessary corrections
|
|
157
|
+
self.precession_angle = precession_angle
|
|
158
|
+
if precession_angle ==0:
|
|
159
|
+
self.precession_angle=None
|
|
119
160
|
|
|
120
161
|
|
|
121
162
|
|
|
@@ -218,10 +259,21 @@ class SAEDProcessor:
|
|
|
218
259
|
I = I / cos3
|
|
219
260
|
else: # assume units are already in s (1/Å)
|
|
220
261
|
q = r_centers * self.scale * 2 * np.pi
|
|
221
|
-
|
|
222
|
-
|
|
223
262
|
|
|
224
263
|
|
|
264
|
+
# perform intensity corrections if precession is used
|
|
265
|
+
if self.precession_angle is not None:
|
|
266
|
+
# Convert precession angle from degrees to radians
|
|
267
|
+
alpha_rad = np.radians(self.precession_angle)
|
|
268
|
+
R0 = 2 * np.pi * np.sin(alpha_rad) / self.metadata['wavelength']
|
|
269
|
+
# Apply the correction factor: I_corrected = I / q*racine(1-q/2R0)) where R0=2pi*prec_angle/lambda
|
|
270
|
+
I = I / (q * np.sqrt(1 - q / (2 * R0)))
|
|
271
|
+
print("Intensity corrections induced by precession have been performed.\n")
|
|
272
|
+
# limit on qmax imposed by precession angle:
|
|
273
|
+
qmax_prec = np.sin(alpha_rad)*4*np.pi / self.metadata['wavelength']
|
|
274
|
+
print(f'Intensity corrections impose qmax = {qmax_prec:.2f} $\AA^{-1}$')
|
|
275
|
+
print('See K. Gjonnes Ultramicroscopy 69 1-11 (1997) for more details')
|
|
276
|
+
|
|
225
277
|
if plot:
|
|
226
278
|
plt.figure()
|
|
227
279
|
plt.semilogy(q, I)
|
|
@@ -230,10 +282,9 @@ class SAEDProcessor:
|
|
|
230
282
|
plt.title('Azimuthally Integrated SAED Pattern')
|
|
231
283
|
plt.grid()
|
|
232
284
|
plt.show()
|
|
233
|
-
|
|
234
285
|
return q, I
|
|
235
|
-
|
|
236
|
-
def plot(self,vmin=-4, vmax=0,cmap='jet',display_mask=False):
|
|
286
|
+
|
|
287
|
+
def plot(self,vmin=-4, vmax=0,cmap='jet',display_mask=False,outputfile=None):
|
|
237
288
|
plt.figure()
|
|
238
289
|
if display_mask:
|
|
239
290
|
|
|
@@ -251,28 +302,57 @@ class SAEDProcessor:
|
|
|
251
302
|
plt.imshow(self.img/np.max(self.img), cmap=cmap, norm=LogNorm(vmin=10**(vmin), vmax=10**(vmax)))
|
|
252
303
|
#plot center as wihte cross
|
|
253
304
|
plt.plot(self.center[0], self.center[1], 'w+', markersize=8)
|
|
305
|
+
if outputfile is not None:
|
|
306
|
+
plt.savefig(outputfile, dpi=300, bbox_inches='tight')
|
|
307
|
+
|
|
254
308
|
|
|
309
|
+
def save_thumbnail(self, outputfile=None):
|
|
310
|
+
"""
|
|
311
|
+
Display a thumbnail of the diffraction image with the detected beam centre.
|
|
312
|
+
|
|
313
|
+
Parameters
|
|
314
|
+
----------
|
|
315
|
+
outputfile : str, optional
|
|
316
|
+
If provided, save the thumbnail to this file path. Default is ``None`` (no saving).
|
|
317
|
+
"""
|
|
318
|
+
plt.figure(figsize=(6, 6))
|
|
319
|
+
plt.imshow(self.img, cmap='gray')
|
|
320
|
+
plt.axis('off')
|
|
321
|
+
if outputfile is not None:
|
|
322
|
+
plt.savefig(outputfile, dpi=300, bbox_inches='tight')
|
|
323
|
+
|
|
255
324
|
|
|
256
325
|
def plot_recalibrated_image(self, **kwargs):
|
|
257
326
|
"""
|
|
258
327
|
Display the diffraction image with the detected beam centre.
|
|
259
328
|
|
|
260
|
-
Runs
|
|
261
|
-
|
|
262
|
-
|
|
329
|
+
Runs the beam-centre detection method selected by ``self.amorphous``
|
|
330
|
+
(set at initialisation) with ``plot=True`` to trigger the
|
|
331
|
+
diagnostic figure, using ``self.center`` as the initial estimate.
|
|
332
|
+
``self.center`` is updated with the result.
|
|
263
333
|
|
|
264
334
|
Parameters
|
|
265
335
|
----------
|
|
266
336
|
**kwargs
|
|
267
|
-
Extra keyword arguments forwarded to
|
|
268
|
-
:
|
|
269
|
-
``
|
|
270
|
-
|
|
337
|
+
Extra keyword arguments forwarded to the underlying detection
|
|
338
|
+
function:
|
|
339
|
+
- if ``self.amorphous`` is ``True``, forwarded to
|
|
340
|
+
:func:`recalibrate_from_isocurve` (e.g. ``n_levels``,
|
|
341
|
+
``level_range``, ``rms_rel_max``, ``min_arc_deg``,
|
|
342
|
+
``cluster_window``, ``initial_center``);
|
|
343
|
+
- if ``self.amorphous`` is ``False``, forwarded to
|
|
344
|
+
:func:`center_calc_ediff` (e.g. ``detection``,
|
|
345
|
+
``refinement``, ``icut``, ``rtype``, ``downsample``).
|
|
271
346
|
"""
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
initial_center=self.center
|
|
275
|
-
|
|
347
|
+
if self.amorphous:
|
|
348
|
+
# Extract initial_center from kwargs, defaulting to self.center if not provided
|
|
349
|
+
initial_center = kwargs.pop('initial_center', self.center)
|
|
350
|
+
c_x, c_y = recalibrate_from_isocurve(
|
|
351
|
+
self.img, mask=_mask_as_array(self.mask), plot=True,
|
|
352
|
+
initial_center=initial_center, **kwargs
|
|
353
|
+
)
|
|
354
|
+
else:
|
|
355
|
+
c_x, c_y = center_calc_ediff(self.img, plot=True, **kwargs)
|
|
276
356
|
self.center = (c_x, c_y)
|
|
277
357
|
|
|
278
358
|
def inspect_histogram(self, bins=256, log_scale=True, exclude_zero=False,
|
|
@@ -406,7 +486,8 @@ class SAEDProcessor:
|
|
|
406
486
|
qmin=1.5,
|
|
407
487
|
qmax=24,
|
|
408
488
|
qmaxinst=24,
|
|
409
|
-
rpoly=1.4
|
|
489
|
+
rpoly=1.4
|
|
490
|
+
):
|
|
410
491
|
"""
|
|
411
492
|
Extract the ePDF from the SAED data (convenience wrapper).
|
|
412
493
|
|
|
@@ -441,6 +522,19 @@ class SAEDProcessor:
|
|
|
441
522
|
Q-range limits in Å⁻¹ for PDF computation.
|
|
442
523
|
rpoly : float, optional
|
|
443
524
|
Polynomial background degree control (PDFgetX3 convention).
|
|
525
|
+
correct_multiple_scattering : bool, optional
|
|
526
|
+
If ``True``, apply the elastic multiple-scattering correction
|
|
527
|
+
(see :func:`~epdfsuite.multiple_scattering.correct_multiple_scattering`)
|
|
528
|
+
to the sample intensity before PDF extraction, using ``D``,
|
|
529
|
+
``HV`` and ``density``. Default is ``False``.
|
|
530
|
+
D : float, optional
|
|
531
|
+
Nanoparticle diameter (nm), used to estimate the thickness
|
|
532
|
+
traversed by the beam (``t = 2/3 * D``). Default is 15.
|
|
533
|
+
HV : float, optional
|
|
534
|
+
Accelerating voltage (kV). Default is 200.
|
|
535
|
+
density : float, optional
|
|
536
|
+
Mass density of the sample (g/cm³), used to estimate the
|
|
537
|
+
elastic mean free path. Default is 19.3 (Au).
|
|
444
538
|
|
|
445
539
|
Returns
|
|
446
540
|
-------
|
|
@@ -471,7 +565,7 @@ class SAEDProcessor:
|
|
|
471
565
|
qmin=qmin,
|
|
472
566
|
qmax=qmax,
|
|
473
567
|
qmaxinst=qmaxinst,
|
|
474
|
-
rpoly=rpoly
|
|
568
|
+
rpoly=rpoly
|
|
475
569
|
)
|
|
476
570
|
|
|
477
571
|
|
|
@@ -492,7 +586,8 @@ def extract_epdf(sample_processor,
|
|
|
492
586
|
qmin=1.5,
|
|
493
587
|
qmax=24,
|
|
494
588
|
qmaxinst=24,
|
|
495
|
-
rpoly=1.4
|
|
589
|
+
rpoly=1.4
|
|
590
|
+
):
|
|
496
591
|
"""
|
|
497
592
|
Extract the electron Pair Distribution Function (ePDF) from SAED data.
|
|
498
593
|
|
|
@@ -530,6 +625,7 @@ def extract_epdf(sample_processor,
|
|
|
530
625
|
background fitting.
|
|
531
626
|
rpoly : float, optional
|
|
532
627
|
Polynomial degree control (PDFgetX3 convention). Default is 1.4.
|
|
628
|
+
|
|
533
629
|
|
|
534
630
|
Returns
|
|
535
631
|
-------
|
|
@@ -6,7 +6,7 @@ from .camera_library import DETECTOR_LIBRARY
|
|
|
6
6
|
import numpy as np
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
def extract_camera_type(metadata, detector_lib=DETECTOR_LIBRARY):
|
|
9
|
+
def extract_camera_type(metadata, original_metadata=None, detector_lib=DETECTOR_LIBRARY):
|
|
10
10
|
"""
|
|
11
11
|
Identify the camera type from HyperSpy metadata using regex alias matching.
|
|
12
12
|
|
|
@@ -17,6 +17,9 @@ def extract_camera_type(metadata, detector_lib=DETECTOR_LIBRARY):
|
|
|
17
17
|
----------
|
|
18
18
|
metadata : HyperSpy metadata object
|
|
19
19
|
Metadata loaded from a DM4 (or other HyperSpy-supported) file.
|
|
20
|
+
original_metadata : HyperSpy metadata object, optional
|
|
21
|
+
Raw original metadata tree (for example ``image.original_metadata``)
|
|
22
|
+
scanned as a fallback when ``General.title`` is not camera-specific.
|
|
20
23
|
detector_lib : dict, optional
|
|
21
24
|
Detector library to search. Defaults to the built-in
|
|
22
25
|
:data:`DETECTOR_LIBRARY`.
|
|
@@ -28,39 +31,98 @@ def extract_camera_type(metadata, detector_lib=DETECTOR_LIBRARY):
|
|
|
28
31
|
camera_title : str or None
|
|
29
32
|
Raw title string found in the metadata, or ``None`` if unavailable.
|
|
30
33
|
"""
|
|
34
|
+
def _match_from_title(title):
|
|
35
|
+
if not isinstance(title, str):
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
title_clean = title.strip()
|
|
39
|
+
if not title_clean:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
# First, search for exact match
|
|
43
|
+
if title_clean in detector_lib:
|
|
44
|
+
return title_clean, title_clean
|
|
45
|
+
|
|
46
|
+
# Then, search by regex on aliases
|
|
47
|
+
title_lower = title_clean.lower()
|
|
48
|
+
for camera_key, params in detector_lib.items():
|
|
49
|
+
if 'aliases' not in params:
|
|
50
|
+
continue
|
|
51
|
+
for alias_pattern in params['aliases']:
|
|
52
|
+
try:
|
|
53
|
+
pattern = re.compile(alias_pattern, re.IGNORECASE)
|
|
54
|
+
if pattern.search(title_lower):
|
|
55
|
+
return camera_key, title_clean
|
|
56
|
+
except re.error:
|
|
57
|
+
# If not valid regex, search as substring
|
|
58
|
+
if alias_pattern.lower() in title_lower:
|
|
59
|
+
return camera_key, title_clean
|
|
60
|
+
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
def _collect_camera_candidates(obj, prefix=''):
|
|
64
|
+
"""Collect string values from camera-related metadata nodes."""
|
|
65
|
+
candidates = []
|
|
66
|
+
camera_like_keys = (
|
|
67
|
+
'camera', 'detector', 'device', 'source', 'signal_name',
|
|
68
|
+
'device_name', 'source_model', 'name', 'title',
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
if hasattr(obj, 'keys'):
|
|
73
|
+
for key in obj.keys():
|
|
74
|
+
value = obj[key]
|
|
75
|
+
key_str = str(key)
|
|
76
|
+
path = f"{prefix}.{key_str}" if prefix else key_str
|
|
77
|
+
key_lower = key_str.lower()
|
|
78
|
+
|
|
79
|
+
if isinstance(value, str) and any(k in key_lower for k in camera_like_keys):
|
|
80
|
+
candidates.append((path, value))
|
|
81
|
+
|
|
82
|
+
if hasattr(value, 'keys'):
|
|
83
|
+
candidates.extend(_collect_camera_candidates(value, path))
|
|
84
|
+
except Exception:
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
return candidates
|
|
88
|
+
|
|
89
|
+
tried_titles = []
|
|
90
|
+
|
|
31
91
|
try:
|
|
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
|
-
|
|
92
|
+
# Priority 1: General.title if present
|
|
93
|
+
if hasattr(metadata, 'General') and hasattr(metadata.General, 'title'):
|
|
94
|
+
title = metadata.General.title
|
|
95
|
+
tried_titles.append(title)
|
|
96
|
+
matched = _match_from_title(title)
|
|
97
|
+
if matched is not None:
|
|
98
|
+
return matched
|
|
99
|
+
|
|
100
|
+
# Priority 2: scan metadata and original_metadata for camera-like fields
|
|
101
|
+
candidates = []
|
|
102
|
+
if metadata is not None:
|
|
103
|
+
candidates.extend(_collect_camera_candidates(metadata, 'metadata'))
|
|
104
|
+
if original_metadata is not None:
|
|
105
|
+
candidates.extend(_collect_camera_candidates(original_metadata, 'original_metadata'))
|
|
106
|
+
|
|
107
|
+
seen = set()
|
|
108
|
+
for _, value in candidates:
|
|
109
|
+
title = value.strip() if isinstance(value, str) else None
|
|
110
|
+
if not title or title in seen:
|
|
111
|
+
continue
|
|
112
|
+
seen.add(title)
|
|
113
|
+
tried_titles.append(title)
|
|
114
|
+
|
|
115
|
+
matched = _match_from_title(title)
|
|
116
|
+
if matched is not None:
|
|
117
|
+
return matched
|
|
118
|
+
|
|
119
|
+
if tried_titles:
|
|
120
|
+
print(" ⚠ No match found in aliases")
|
|
121
|
+
return None, tried_titles[0]
|
|
122
|
+
|
|
61
123
|
except Exception as e:
|
|
62
124
|
print(f"Error extracting camera type: {e}")
|
|
63
|
-
|
|
125
|
+
|
|
64
126
|
return None, None
|
|
65
127
|
|
|
66
128
|
def _search_metadata_recursive(obj, target_keys, depth=0, max_depth=10):
|
|
@@ -306,7 +368,7 @@ def load_data(file, normalize=True, verbose=True):
|
|
|
306
368
|
raw_image = image.data
|
|
307
369
|
|
|
308
370
|
# Extract detector info automatically
|
|
309
|
-
camera_key, camera_title = extract_camera_type(metadata)
|
|
371
|
+
camera_key, camera_title = extract_camera_type(metadata, getattr(image, 'original_metadata', None))
|
|
310
372
|
|
|
311
373
|
# Extract wavelength information
|
|
312
374
|
wavelength_info = extract_wavelength(metadata)
|
|
@@ -2,6 +2,7 @@ import numpy as np
|
|
|
2
2
|
from skimage import measure
|
|
3
3
|
from pyFAI.utils.ellipse import fit_ellipse as pyfai_fit_ellipse
|
|
4
4
|
import matplotlib.pyplot as plt
|
|
5
|
+
import ediff as ed
|
|
5
6
|
|
|
6
7
|
def _fit_circle_algebraic(y_pts, x_pts):
|
|
7
8
|
"""Algebraic (Kåsa) circle fit on a set of 2-D points.
|
|
@@ -129,6 +130,12 @@ def recalibrate_from_isocurve(image, n_levels=7, level_range=(0.15, 0.75),
|
|
|
129
130
|
# Boolean mask of invalid pixels
|
|
130
131
|
invalid = np.asarray(mask, dtype=bool) if mask is not None \
|
|
131
132
|
else np.zeros(img.shape, dtype=bool)
|
|
133
|
+
if invalid.shape != img.shape:
|
|
134
|
+
raise ValueError(
|
|
135
|
+
f"recalibrate_from_isocurve: mask shape {invalid.shape} does not "
|
|
136
|
+
f"match image shape {img.shape}. Make sure the mask was drawn "
|
|
137
|
+
"for this specific image."
|
|
138
|
+
)
|
|
132
139
|
|
|
133
140
|
# --- Normalise using only VALID pixels ---
|
|
134
141
|
valid_vals = img[~invalid]
|
|
@@ -309,8 +316,8 @@ def recalibrate_from_isocurve(image, n_levels=7, level_range=(0.15, 0.75),
|
|
|
309
316
|
label=f'Initial ({x_rough:.0f}, {y_rough:.0f})')
|
|
310
317
|
axes[0].plot(x_c, y_c, 'r+', markersize=16, markeredgewidth=2.5,
|
|
311
318
|
label=f'Centre ({x_c:.1f}, {y_c:.1f})')
|
|
312
|
-
axes[0].set_title('Iso-intensity contours', fontsize=13)
|
|
313
|
-
axes[0].legend(fontsize=
|
|
319
|
+
#axes[0].set_title('Iso-intensity contours', fontsize=13)
|
|
320
|
+
axes[0].legend(fontsize=12, loc='lower right')
|
|
314
321
|
axes[0].grid(True, alpha=0.3)
|
|
315
322
|
|
|
316
323
|
# Panel 2: cluster members coloured by RMS, outliers as grey ×
|
|
@@ -322,31 +329,190 @@ def recalibrate_from_isocurve(image, n_levels=7, level_range=(0.15, 0.75),
|
|
|
322
329
|
sc = axes[1].scatter(x_centers[in_cluster], y_centers[in_cluster],
|
|
323
330
|
c=rms_arr[in_cluster], cmap='RdYlGn_r', s=40, zorder=3,
|
|
324
331
|
label=f'Cluster [{int(in_cluster.sum())}]')
|
|
325
|
-
plt.colorbar(sc, ax=axes[1], label='RMS residual (px)')
|
|
332
|
+
#plt.colorbar(sc, ax=axes[1], label='RMS residual (px)')
|
|
326
333
|
if x_rough is not None:
|
|
327
334
|
axes[1].plot(x_rough, y_rough, 'b+', markersize=14,
|
|
328
335
|
markeredgewidth=2,
|
|
329
336
|
label=f'Initial ({x_rough:.0f}, {y_rough:.0f})')
|
|
330
337
|
axes[1].plot(x_c, y_c, 'r*', markersize=18, zorder=4,
|
|
331
338
|
label=f'Median ({x_c:.1f}, {y_c:.1f})')
|
|
332
|
-
axes[1].set_title('Centre estimates – cluster analysis', fontsize=13)
|
|
333
|
-
axes[1].legend(fontsize=
|
|
339
|
+
#axes[1].set_title('Centre estimates – cluster analysis', fontsize=13)
|
|
340
|
+
axes[1].legend(fontsize=12)
|
|
334
341
|
axes[1].set_aspect('equal', 'box')
|
|
335
342
|
axes[1].invert_yaxis()
|
|
336
343
|
axes[1].grid(True, alpha=0.3)
|
|
337
344
|
|
|
338
345
|
for ax in axes:
|
|
339
|
-
ax.set_xlabel('X (pixels)', fontsize=
|
|
340
|
-
ax.set_ylabel('Y (pixels)', fontsize=
|
|
346
|
+
ax.set_xlabel('X (pixels)', fontsize=14)
|
|
347
|
+
ax.set_ylabel('Y (pixels)', fontsize=14)
|
|
341
348
|
n_rej = len(_rejected)
|
|
342
349
|
n_out = int((~in_cluster).sum())
|
|
343
|
-
fig.suptitle(
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
)
|
|
350
|
+
#fig.suptitle(
|
|
351
|
+
# f'recalibrate_from_isocurve | cluster: {int(in_cluster.sum())} pts'
|
|
352
|
+
# f' | outliers: {n_out} | shape-rejected: {n_rej}'
|
|
353
|
+
# f' | centre = ({x_c:.2f}, {y_c:.2f}) px',
|
|
354
|
+
# fontsize=11
|
|
355
|
+
#)
|
|
349
356
|
fig.tight_layout()
|
|
350
357
|
plt.show()
|
|
351
358
|
|
|
352
359
|
return x_c, y_c
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _plot_center_log(image, x_c, y_c, r=None, title=None, csquare=None,
|
|
363
|
+
axes_off=False, out_file=None, out_dpi=200):
|
|
364
|
+
"""Diagnostic plot: log-scaled, normalised image with the fitted centre.
|
|
365
|
+
|
|
366
|
+
Parameters
|
|
367
|
+
----------
|
|
368
|
+
image : ndarray
|
|
369
|
+
2-D image (original intensity scale) to display.
|
|
370
|
+
x_c, y_c : float
|
|
371
|
+
Fitted centre coordinates (pixels), in the same frame as *image*.
|
|
372
|
+
r : float or None, optional
|
|
373
|
+
Radius (pixels) of the refinement ring; drawn as a circle if given.
|
|
374
|
+
title : str or None, optional
|
|
375
|
+
Axes title.
|
|
376
|
+
csquare : int or None, optional
|
|
377
|
+
If given, zoom on the central square of this size (pixels).
|
|
378
|
+
axes_off : bool, optional
|
|
379
|
+
If ``True``, hide the axes ticks/labels.
|
|
380
|
+
out_file : str or None, optional
|
|
381
|
+
If given, save the figure to this path.
|
|
382
|
+
out_dpi : int, optional
|
|
383
|
+
DPI used when saving *out_file*. Default is ``200``.
|
|
384
|
+
"""
|
|
385
|
+
from matplotlib.colors import LogNorm
|
|
386
|
+
|
|
387
|
+
img = np.asarray(image, dtype=float)
|
|
388
|
+
# Normalise to [0, 1] on valid (finite) pixels, then shift away from 0
|
|
389
|
+
# so the whole range can be displayed on a log scale.
|
|
390
|
+
finite = np.isfinite(img)
|
|
391
|
+
vmin0 = np.nanpercentile(img[finite], 0.5)
|
|
392
|
+
vmax0 = np.nanpercentile(img[finite], 99.5)
|
|
393
|
+
img_norm = np.clip((img - vmin0) / (vmax0 - vmin0 + 1e-10), 1e-4, 1.0)
|
|
394
|
+
|
|
395
|
+
fig, ax = plt.subplots(figsize=(6, 6))
|
|
396
|
+
im = ax.imshow(img_norm, cmap='inferno', origin='upper',
|
|
397
|
+
norm=LogNorm(vmin=1e-4, vmax=1.0))
|
|
398
|
+
ax.scatter(x_c, y_c, color='cyan', marker='+', s=140, lw=2,
|
|
399
|
+
label=f'centre ({x_c:.1f}, {y_c:.1f})')
|
|
400
|
+
if r is not None:
|
|
401
|
+
circ = plt.Circle((x_c, y_c), r, color='cyan', fill=False, lw=1.2,
|
|
402
|
+
label='refinement ring')
|
|
403
|
+
ax.add_patch(circ)
|
|
404
|
+
|
|
405
|
+
if title:
|
|
406
|
+
ax.set_title(title)
|
|
407
|
+
ax.legend(loc='upper right', frameon=True, fontsize=9)
|
|
408
|
+
fig.colorbar(im, ax=ax, label='Normalised intensity (log)')
|
|
409
|
+
|
|
410
|
+
if csquare is not None:
|
|
411
|
+
h, w = img.shape
|
|
412
|
+
half = csquare / 2.0
|
|
413
|
+
ax.set_xlim(x_c - half, x_c + half)
|
|
414
|
+
ax.set_ylim(y_c + half, y_c - half)
|
|
415
|
+
|
|
416
|
+
if axes_off:
|
|
417
|
+
ax.axis('off')
|
|
418
|
+
else:
|
|
419
|
+
ax.set_xlabel('X (pixels)')
|
|
420
|
+
ax.set_ylabel('Y (pixels)')
|
|
421
|
+
|
|
422
|
+
fig.tight_layout()
|
|
423
|
+
if out_file is not None:
|
|
424
|
+
fig.savefig(out_file, dpi=out_dpi)
|
|
425
|
+
plt.show()
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def center_calc_ediff(image, detection='hough', refinement='sum', icut=150,
|
|
429
|
+
rtype=0, verbose=3, plot=False, csquare=None,
|
|
430
|
+
axes_off=False, out_file=None, out_dpi=200,
|
|
431
|
+
downsample='auto', target_size=512, **kwargs):
|
|
432
|
+
"""Find the beam centre using the ``ediff`` library.
|
|
433
|
+
|
|
434
|
+
Thin wrapper around ``ediff.center.CenterLocator``, kept consistent
|
|
435
|
+
with :func:`recalibrate_from_isocurve` by returning an ``(x_c, y_c)``
|
|
436
|
+
tuple instead of the raw ``CenterLocator`` object.
|
|
437
|
+
|
|
438
|
+
Parameters
|
|
439
|
+
----------
|
|
440
|
+
image : ndarray
|
|
441
|
+
2-D image as a numpy array (passed straight to ``CenterLocator``,
|
|
442
|
+
which handles arrays, file paths and ``Diffractogram2D`` objects).
|
|
443
|
+
detection, refinement, icut, rtype, verbose : optional
|
|
444
|
+
Forwarded to ``ediff.center.CenterLocator``. See that class's
|
|
445
|
+
docstring for details.
|
|
446
|
+
plot : bool, optional
|
|
447
|
+
If ``True``, show a diagnostic figure (log-scaled, normalised image)
|
|
448
|
+
with the fitted centre and refinement ring overlaid. Default is
|
|
449
|
+
``False``.
|
|
450
|
+
csquare, axes_off, out_file, out_dpi : optional
|
|
451
|
+
Forwarded to the internal plotting helper when ``plot`` is ``True``
|
|
452
|
+
(zoom window, hide axes, save to file, output DPI).
|
|
453
|
+
downsample : int, 'auto' or None, optional
|
|
454
|
+
Binning factor applied to *image* before it is handed to
|
|
455
|
+
``CenterLocator``. Default is ``'auto'``: the factor is computed
|
|
456
|
+
from *target_size* so the largest image dimension ends up close to
|
|
457
|
+
it (e.g. a 4096x4096 image with the default ``target_size=512``
|
|
458
|
+
gives ``downsample=8``). Pass an explicit ``int`` to override, or
|
|
459
|
+
``1``/``None`` to disable binning entirely.
|
|
460
|
+
``ediff``'s ``detection='hough'`` scans a **hard-coded** radius
|
|
461
|
+
range of 50-120 px and rebuilds a full-image-sized Hough
|
|
462
|
+
accumulator for every tested radius: on a large image this is both
|
|
463
|
+
very slow and likely to miss the actual ring (if its radius in
|
|
464
|
+
pixels is outside 50-120). Downsampling brings the image size and
|
|
465
|
+
the ring radius back into a range Hough can handle quickly and
|
|
466
|
+
correctly. The returned centre is automatically rescaled back to
|
|
467
|
+
the original (full-resolution) pixel coordinates.
|
|
468
|
+
target_size : int, optional
|
|
469
|
+
Target size (pixels) used to compute *downsample* when it is set
|
|
470
|
+
to ``'auto'``. Default is ``512``.
|
|
471
|
+
**kwargs
|
|
472
|
+
Any other keyword argument accepted by ``ediff.center.CenterLocator``
|
|
473
|
+
(e.g. ``masking``, ``ellipse``, ``cintensity``, ...).
|
|
474
|
+
|
|
475
|
+
Returns
|
|
476
|
+
-------
|
|
477
|
+
x_c, y_c : float
|
|
478
|
+
Refined centre coordinates (``center.x``, ``center.y``), expressed
|
|
479
|
+
in the original (full-resolution) pixel grid.
|
|
480
|
+
"""
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
img = np.asarray(image, dtype=float)
|
|
484
|
+
|
|
485
|
+
if downsample == 'auto':
|
|
486
|
+
downsample = max(1, round(max(img.shape) / target_size))
|
|
487
|
+
|
|
488
|
+
if downsample and downsample > 1:
|
|
489
|
+
from skimage.transform import rescale
|
|
490
|
+
img = rescale(img, 1.0 / downsample, anti_aliasing=True,
|
|
491
|
+
preserve_range=True)
|
|
492
|
+
|
|
493
|
+
center = ed.center.CenterLocator(
|
|
494
|
+
img,
|
|
495
|
+
detection=detection,
|
|
496
|
+
refinement=refinement,
|
|
497
|
+
icut=icut,
|
|
498
|
+
rtype=rtype,
|
|
499
|
+
verbose=verbose,
|
|
500
|
+
**kwargs,
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
x_c, y_c = center.x, center.y
|
|
504
|
+
r = getattr(center.center2, 'rr', None) if hasattr(center, 'center2') \
|
|
505
|
+
else None
|
|
506
|
+
|
|
507
|
+
if plot:
|
|
508
|
+
_plot_center_log(img, x_c, y_c, r=r,
|
|
509
|
+
title=f'Center :: {detection}/{refinement}',
|
|
510
|
+
csquare=csquare, axes_off=axes_off,
|
|
511
|
+
out_file=out_file, out_dpi=out_dpi)
|
|
512
|
+
|
|
513
|
+
if downsample and downsample > 1:
|
|
514
|
+
if r is not None:
|
|
515
|
+
r *= downsample
|
|
516
|
+
x_c *= downsample
|
|
517
|
+
y_c *= downsample
|
|
518
|
+
return x_c, y_c
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|