-
Notifications
You must be signed in to change notification settings - Fork 59
/
measure.py
1402 lines (1105 loc) · 47.7 KB
/
measure.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
"""Module to describe the detection of scattered electron waves."""
from collections.abc import Iterable, Callable
from copy import copy
from typing import Sequence, Tuple, List, Union
from abc import ABCMeta, abstractmethod
import h5py
import imageio
import numpy as np
import scipy.misc
import scipy.ndimage
from scipy import ndimage
from scipy.interpolate import interp1d, interp2d, interpn
from scipy.ndimage import gaussian_filter
from abtem.base_classes import Grid
from abtem.cpu_kernels import abs2
from abtem.device import asnumpy
from abtem.utils import periodic_crop, tapered_cutoff
from abtem.visualize.mpl import show_measurement_2d, show_measurement_1d
from abtem.utils import fft_interpolate_2d
from ase import Atom
class Calibration:
"""
Calibration object
The calibration object represents the sampling of a uniformly sampled Measurement.
Parameters
----------
offset: float
The lower bound of the sampling points.
sampling: float
The distance between sampling points.
units: str
The units of the calibration shown in plots.
name: str
The name of this calibration to be shown in plots.
"""
def __init__(self, offset: float, sampling: float, units: str, name: str = '', endpoint: bool = True,
adjustable: bool = True):
self.offset = offset
self.sampling = sampling
self.units = units
self.name = name
self.endpoint = endpoint
def __eq__(self, other):
return (np.isclose(self.offset, other.offset) &
np.isclose(self.sampling, other.sampling) &
(self.units == other.units) &
(self.name == other.name))
def extent(self, n):
return (self.offset, n * self.sampling + self.offset)
def coordinates(self, n):
return np.linspace(*self.extent(n), n, endpoint=False)
def __copy__(self):
return self.__class__(self.offset, self.sampling, self.units, self.name)
def copy(self):
"""
Make a copy.
"""
return copy(self)
def fourier_space_offset(n: int, d: float):
"""
Calculate the calibration offset of a Fourier space measurement.
Parameters
----------
n : int
Number of sampling points.
d : float
Real space sampling density.
"""
if n % 2 == 0:
return -1 / (2 * d)
else:
return -1 / (2 * d) + 1 / (2 * d * n)
def calibrations_from_grid(gpts: Sequence[int],
sampling: Sequence[float],
names: Sequence[str] = None,
units: str = None,
fourier_space: bool = False,
scale_factor: float = 1.0) -> Tuple[Calibration]:
"""
Returns the spatial calibrations for a given computational grid and sampling.
Parameters
----------
gpts: list of int
Number of grid points in the x and y directions.
sampling: list of float
Sampling of the potential in Å.
names: list of str, optional
The name of this calibration.
units: str, optional
Units for the calibration.
fourier_space: bool, optional
Setting for calibrating either in the reciprocal or real space. Default is False.
scale_factor: float, optional
Scaling factor for the calibration. Default is 1.0.
Returns
-------
calibrations: Tuple of Calibrations
"""
if names is None:
if fourier_space:
names = ('alpha_x', 'alpha_y')
else:
names = ('x', 'y')
elif len(names) != len(gpts):
raise RuntimeError()
if units is None:
if fourier_space:
units = '1 / Å'
else:
units = 'Å'
calibrations = ()
if fourier_space:
for name, n, d in zip(names, gpts, sampling):
r = n * d
offset = fourier_space_offset(n, d)
calibrations += (Calibration(offset * scale_factor, 1 / r * scale_factor, units, name),)
else:
for name, d in zip(names, sampling):
calibrations += (Calibration(0., d * scale_factor, units, name),)
return calibrations
def grid_from_calibrations(calibrations, extent=None, gpts=None) -> Grid:
if (extent is None) and (gpts is None):
raise RuntimeError
sampling = ()
for calibration in calibrations:
sampling += (calibration.sampling,)
return Grid(extent=extent, gpts=gpts, sampling=sampling)
class AbstractMeasurement(metaclass=ABCMeta):
def __init__(self, array: np.array, name='', units=''):
self._array = asnumpy(array)
self._name = name
self._units = units
@property
@abstractmethod
def calibrations(self):
pass
@property
def array(self):
return self._array
@property
def shape(self) -> Tuple[int]:
"""
The shape of the measurement array.
"""
return self._array.shape
@property
def units(self) -> 'str':
"""
The units of the array values to be displayed in plots.
"""
return self._units
@property
def name(self) -> 'str':
"""
The name of the array values to be displayed in plots.
"""
return self._name
@property
def dimensions(self) -> int:
"""
The measurement dimensions.
"""
return len(self.array.shape)
@abstractmethod
def show(self):
pass
# TODO : ensure diffraction pattern centering
class Measurement(AbstractMeasurement):
"""
Measurement object.
The measurement object is used for representing the output of a TEM simulation. For example a line profile, an image
or a collection of diffraction patterns.
Parameters
----------
array: ndarray
The array representing the measurements. The array can be any dimension.
calibrations: list of Calibration objects
The calibration for each dimension of the measurement array.
units: str
The units of the array values to be displayed in plots.
name: str
The name of the array values to be displayed in plots.
"""
def __init__(self,
array: Union[np.ndarray, 'Measurement'],
calibrations: Union[Calibration, Sequence[Union[Calibration, None]]] = None,
units: str = '',
name: str = ''):
if issubclass(array.__class__, self.__class__):
measurement = array
array = measurement.array
calibrations = measurement.calibrations
units = measurement.array
name = measurement.name
if not isinstance(calibrations, Iterable):
calibrations = [calibrations] * len(array.shape)
if len(calibrations) != len(array.shape):
raise RuntimeError(
'The number of calibrations must equal the number of array dimensions. For undefined use None.')
self._calibrations = calibrations
super().__init__(array=array, name=name, units=units)
def __getitem__(self, args):
# TODO: check that edge cases work
if isinstance(args, Iterable):
args += (slice(None),) * (len(self.array.shape) - len(args))
else:
args = (args,) + (slice(None),) * (len(self.array.shape) - 1)
new_array = self.array[args]
new_calibrations = []
for i, (arg, calibration) in enumerate(zip(args, self.calibrations)):
if isinstance(arg, slice):
if calibration is None:
new_calibrations.append(None)
else:
if arg.start is None:
offset = calibration.offset
else:
offset = arg.start * calibration.sampling + calibration.offset
new_calibrations.append(Calibration(offset=offset,
sampling=calibration.sampling,
units=calibration.units, name=calibration.name))
elif isinstance(arg, Iterable):
new_calibrations.append(None)
elif not isinstance(arg, int):
raise TypeError('Indices must be integers or slices, not float')
return self.__class__(new_array, new_calibrations)
@property
def calibration_limits(self):
limits = []
for calibration, size in zip(self.calibrations, self.array.shape):
if calibration is None:
limits.append((None,) * 2)
else:
limits.append((calibration.offset, calibration.offset + size * calibration.sampling))
return limits
@property
def calibration_units(self):
units = []
for calibration, size in zip(self.calibrations, self.array.shape):
if calibration is None:
units.append('')
else:
units.append(calibration.units)
return units
@property
def calibration_names(self):
names = []
for calibration, size in zip(self.calibrations, self.array.shape):
if calibration is None:
names.append('none')
else:
names.append(calibration.name)
return names
def __len__(self):
return self.shape[0]
@property
def array(self) -> np.ndarray:
"""
Array of measurements.
"""
return self._array
def angle(self):
new_measurement = self.copy()
new_measurement._array = np.angle(new_measurement.array)
return new_measurement
def abs(self):
new_measurement = self.copy()
new_measurement._array = np.abs(new_measurement.array)
return new_measurement
@array.setter
def array(self, array: np.ndarray):
"""
Array of measurements.
"""
self._array[:] = array
@property
def calibrations(self) -> List[Union[Calibration, None]]:
"""
The measurement calibrations.
"""
return self._calibrations
def check_match_calibrations(self, other):
for calibration, other_calibration in zip(self.calibrations, other.calibrations):
if not calibration == other_calibration:
raise ValueError('Calibration mismatch, operation not possible.')
def __isub__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
self._array -= other.array
else:
self._array -= asnumpy(other)
return self
def __sub__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
new_array = self.array - other.array
else:
new_array = self._array - asnumpy(other)
return self.__class__(new_array, calibrations=self.calibrations, units=self.units, name=self.name)
def __iadd__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
self._array += other.array
else:
self._array += asnumpy(other)
return self
def __add__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
new_array = self.array + other.array
else:
new_array = self._array + asnumpy(other)
return self.__class__(new_array, calibrations=self.calibrations, units=self.units, name=self.name)
def __imul__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
self._array *= other.array
else:
self._array *= asnumpy(other)
return self
def __mul__(self, other):
new_copy = self.copy()
new_copy *= other
return new_copy
__rmul__ = __mul__
def __itruediv__(self, other):
if isinstance(other, self.__class__):
self.check_match_calibrations(other)
self._array /= other.array
else:
self._array /= asnumpy(other)
return self
def __truediv__(self, other):
new_copy = self.copy()
new_copy /= other
return new_copy
__rtruediv__ = __truediv__
def _reduction(self, reduction_function: Callable, axis: Union[int, Sequence[int]]):
if not isinstance(axis, Iterable):
axis = (axis,)
array = reduction_function(self.array, axis=axis)
axis = [d % len(self.calibrations) for d in axis]
calibrations = [self.calibrations[i] for i in range(len(self.calibrations)) if i not in axis]
return self.__class__(array, calibrations)
def sum(self, axis) -> 'Measurement':
"""
Sum of measurement elements over a given axis.
Parameters
----------
axis: int or tuple of ints
Axis or axes along which a sum is performed. If axis is negative it counts from the last to the first axis.
Returns
-------
Measurement
A measurement with the same shape, but with the specified axis removed.
"""
return self._reduction(np.mean, axis)
def mean(self, axis) -> 'Measurement':
"""
Mean of measurement elements over a given axis.
Parameters
----------
axis: int or tuple of ints
Axis or axes along which a sum is performed. If axis is negative it counts from the last to the first axis.
Returns
-------
Measurement object
A measurement with the same shape, but with the specified axis removed.
"""
return self._reduction(np.mean, axis)
def intensity(self):
if not np.iscomplexobj(self.array):
raise RuntimeError()
new_measurement = self.copy()
new_measurement._array = abs2(new_measurement._array)
return new_measurement
def diffractograms(self, axes: Tuple[int] = None) -> 'Measurement':
"""
Calculate the diffractograms of this measurement.
Parameters
----------
axes : list of int
The axes to Fourier transform.
Returns
-------
Measurement
"""
if axes is None:
if self.dimensions >= 2:
axes = (-2, -1)
else:
axes = (-1,)
array = np.fft.fftn(self.array, axes=axes)
sampling = []
gpts = []
for i in axes:
sampling += [self.calibrations[i].sampling]
gpts += [self.array.shape[i]]
calibrations = calibrations_from_grid(gpts=gpts, sampling=sampling, fourier_space=True)
array = np.fft.fftshift(np.abs(array) ** 2, axes=axes)
return self.__class__(array=array, calibrations=calibrations)
def gaussian_filter(self, sigma: Union[float, Sequence[float]], padding_mode: str = 'wrap'):
"""
Apply gaussian filter to measurement.
Parameters
----------
sigma : float or sequence of float
Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each
axis as a sequence, or as a single number, in which case it is equal for all axes.
padding_mode :
The padding_mode parameter determines how the input array is padded at the border. Different modes can be
specified along each axis. Default value is ‘wrap’.
Returns
-------
Measurement
Blurred measurement.
"""
if not (self.calibrations[-1].units == self.calibrations[-2].units):
raise RuntimeError('the units of the blurred dimensions must match')
# sigma = (sigma / self.calibrations[-2].sampling, sigma / self.calibrations[-1].sampling)
sigma = [s / calibration.sampling for s, calibration in zip(sigma, self.calibrations)]
new_copy = self.copy()
new_copy._array = gaussian_filter(self.array, sigma, mode=padding_mode)
return new_copy
def _interpolate_1d(self, new_sampling: float = None, new_gpts: int = None, padding: str = 'wrap',
kind: str = None) -> 'Measurement':
if kind is None:
kind = 'quadratic'
endpoint = self.calibrations[-1].endpoint
sampling = self.calibrations[-1].sampling
offset = self.calibrations[-1].offset
extent = sampling * (self.array.shape[-1] - endpoint)
new_grid = Grid(extent=extent, gpts=new_gpts, sampling=new_sampling, endpoint=endpoint)
array = np.pad(self.array, ((5,) * 2,), mode=padding)
x = self.calibrations[-1].coordinates(array.shape[-1]) - 5 * sampling
interpolator = interp1d(x, array, kind=kind)
x = np.linspace(offset, offset + extent, new_grid.gpts[0], endpoint=endpoint)
new_array = interpolator(x)
calibrations = [calibration.copy() for calibration in self.calibrations]
calibrations[-1].sampling = new_grid.sampling[0]
return self.__class__(new_array, calibrations, name=self.name, units=self.units)
def _interpolate_2d(self,
new_sampling: Union[float, Tuple[float, float]] = None,
new_gpts: Union[int, Tuple[int, int]] = None,
padding: str = 'wrap',
kind: str = None,
axes=None) -> 'Measurement':
if kind is None:
kind = 'fft'
if not (self.calibrations[-1].units == self.calibrations[-2].units):
raise RuntimeError('the units of the interpolation dimensions must match')
endpoint = tuple([calibration.endpoint for calibration in self.calibrations])
sampling = tuple([calibration.sampling for calibration in self.calibrations])
offset = tuple([calibration.offset for calibration in self.calibrations])
extent = (sampling[0] * (self.array.shape[0] - endpoint[0]),
sampling[1] * (self.array.shape[1] - endpoint[1]))
new_grid = Grid(extent=extent, gpts=new_gpts, sampling=new_sampling, endpoint=endpoint)
if kind.lower() == 'fft':
new_array = fft_interpolate_2d(self.array, new_grid.gpts)
else:
array = np.pad(self.array, ((5,) * 2,) * 2, mode=padding)
x = self.calibrations[0].coordinates(array.shape[0]) - 5 * self.calibrations[0].sampling
y = self.calibrations[1].coordinates(array.shape[1]) - 5 * self.calibrations[1].sampling
interpolator = interp2d(x, y, array.T, kind=kind)
x = np.linspace(offset[0], offset[0] + extent[0], new_grid.gpts[0], endpoint=endpoint[0])
y = np.linspace(offset[1], offset[1] + extent[1], new_grid.gpts[1], endpoint=endpoint[1])
new_array = interpolator(x, y).T
calibrations = []
for calibration, d in zip(self.calibrations, new_grid.sampling):
calibrations.append(copy(calibration))
calibrations[-1].sampling = d
return self.__class__(new_array, calibrations, name=self.name, units=self.units)
def interpolate(self,
new_sampling: Union[float, Tuple[float, float]] = None,
new_gpts: Union[int, Tuple[int, int]] = None,
padding: str = 'wrap',
kind: str = None,
axes=None) -> 'Measurement':
"""
Interpolate a 2d measurement.
Parameters
----------
new_sampling : one or two float, optional
Target measurement sampling. Same units as measurement calibrations.
new_gpts : one or two int, optional
Target measurement gpts.
padding : str, optional
The padding mode as used by numpy.pad.
kind : str, optional
The kind of spline interpolation to use. Default is 'quintic'.
Returns
-------
Measurement object
Interpolated measurement
"""
if self.dimensions == 1:
return self._interpolate_1d(new_sampling=new_sampling, new_gpts=new_gpts, padding=padding, kind=kind)
if self.dimensions == 2:
return self._interpolate_2d(new_sampling=new_sampling, new_gpts=new_gpts, padding=padding, kind=kind)
if len(axes) > 2:
raise ValueError()
array = measurement.array
old_shape = array.shape
# print(old_shape)
# array = array.reshape(array.shape[:2] + (-1,))
axes = (2, 3)
array = np.moveaxis(array, axes, range(len(axes)))
rolled_shape = array.shape
array = array.reshape((-1,) + array.shape[-2:])
array = fft_interpolate_2d(array, (60, 60))
array = array.reshape(rolled_shape[:len(axes)] + array.shape[-2:])
array = np.moveaxis(array, range(len(axes)), axes)
return self._interpolate_2d(new_sampling=new_sampling, new_gpts=new_gpts, padding=padding, kind=kind, axes=axes)
# else:
# raise RuntimeError(f'interpolate not implemented for {self.dimensions}d measurements')
def tile(self, multiples: Sequence[int]) -> 'Measurement':
"""
Construct a measurement by repeating the measurement number of times given by multiples.
Parameters
----------
multiples: sequence of int
The number of repetitions of the measurement along each axis.
Returns
-------
Measurement object
The tiled potential.
"""
new_array = np.tile(self._array, multiples)
return self.__class__(new_array, self.calibrations, name=self.name, units=self.units)
@classmethod
def read(cls, path) -> 'Measurement':
"""
Read measurement from a hdf5 file.
path: str
The path to read the file.
"""
with h5py.File(path, 'r') as f:
datasets = {}
for key in f.keys():
datasets[key] = f.get(key)[()]
calibrations = []
for i in range(len(datasets['offset'])):
if not datasets['is_none'][i]:
calibrations.append(Calibration(offset=datasets['offset'][i],
sampling=datasets['sampling'][i],
units=datasets['units'][i].decode('utf-8'),
name=datasets['name'][i].decode('utf-8')))
else:
calibrations.append(None)
return cls(datasets['array'], calibrations)
def write(self, path, mode='w'):
"""
Write measurement to a hdf5 file.
path: str
The path to write the file.
"""
with h5py.File(path, mode) as f:
f.create_dataset('array', data=self.array)
is_none = []
offsets = []
sampling = []
units = []
names = []
for calibration in self.calibrations:
if calibration is None:
offsets += [0.]
sampling += [0.]
units += ['']
names += ['']
is_none += [True]
else:
offsets += [calibration.offset]
sampling += [calibration.sampling]
units += [calibration.units.encode('utf-8')]
names += [calibration.name.encode('utf-8')]
is_none += [False]
f.create_dataset('offset', data=offsets)
f.create_dataset('sampling', data=sampling)
f.create_dataset('units', (len(units),), 'S10', units)
f.create_dataset('name', (len(names),), 'S10', names)
f.create_dataset('is_none', data=is_none)
return path
def save_as_image(self, path: str):
"""
Write the measurement array to an image file. The array will be normalized and converted to 16-bit integers.
path: str
The path to write the file.
"""
if self.dimensions != 2:
raise RuntimeError('Only 2d measurements can be saved as an image.')
array = (self.array - self.array.min()) / self.array.ptp() * np.iinfo(np.uint16).max
array = array.astype(np.uint16)
imageio.imwrite(path, array.T)
def __copy__(self) -> 'Measurement':
calibrations = []
for calibration in self.calibrations:
calibrations.append(copy(calibration))
return self.__class__(self._array.copy(), calibrations=calibrations)
def copy(self) -> 'Measurement':
"""
Make a copy.
"""
return copy(self)
def squeeze(self) -> 'Measurement':
"""
Remove dimensions of length one from measurement.
Returns
-------
Measurement
"""
new_meaurement = self.copy()
calibrations = [calib for calib, num_elem in zip(self.calibrations, self.array.shape) if num_elem > 1]
new_meaurement._calibrations = calibrations
new_meaurement._array = np.squeeze(asnumpy(new_meaurement.array))
return new_meaurement
def integrate(self, start: float, end: float, axis=-1, interactive=False):
"""
Perform 1d integration measurement from e.g. the FlexibleAnnularDetector
Parameters
----------
start : float
Lower limit of integral in units of the calibration of the given axis.
end : float
Upper limit of integral in units of the calibration of the given axis.
axis : int
The
Returns
-------
Measurement
Integrated measurement.
"""
offset = self.calibrations[axis].offset
sampling = self.calibrations[axis].sampling
calibrations = [copy(calibration) for calibration in self.calibrations]
del calibrations[axis]
def integrate(start, end):
start = int((start - offset) / sampling)
stop = int((end - offset) / sampling)
return self.array[..., start:stop].sum(axis)
new_measurement = Measurement(integrate(start, end), calibrations=calibrations)
if interactive:
from abtem.visualize.interactive import Canvas, MeasurementArtist2d
import ipywidgets as widgets
canvas = Canvas(lock_scale=True)
artist = MeasurementArtist2d()
canvas.artists = {'image': artist}
def update(change):
new_measurement.array[:] = integrate(*change['new'])
artist.measurement = new_measurement.copy()
canvas.adjust_limits_to_artists()
canvas.adjust_labels_to_artists()
update({'new': [start, end]})
slider = widgets.FloatRangeSlider(min=0,
max=sampling * self.array.shape[-1],
value=[start, end],
description='Integration range',
layout=widgets.Layout(width='400px'))
slider.observe(update, 'value')
return new_measurement, widgets.HBox([canvas.figure, slider])
else:
return new_measurement
def interpolate_line(self,
start: Union[Tuple[float, float], Atom],
end: Union[Tuple[float, float], Atom] = None,
angle: float = 0.,
gpts: int = None,
sampling: float = None,
width: float = None,
margin: float = 0.,
interpolation_method: str = 'splinef2d') -> 'LineProfile':
"""
Interpolate 2d measurement along a line.
Parameters
----------
start : two float, Atom
Start point on line [Å].
end : two float, Atom, optional
End point on line [Å].
angle : float, optional
The angle of the line. This is only used when an "end" is not give.
gpts : int
Number of grid points along line.
sampling : float
Sampling rate of grid points along line [1 / Å].
width : float, optional
The interpolation will be averaged across line of this width.
margin : float, optional
The line will be extended by this amount at both ends.
interpolation_method : str, optional
The interpolation method.
Returns
-------
Measurement
Line profile measurement.
"""
from abtem.scan import LineScan
measurement = self.squeeze()
if measurement.dimensions != 2:
raise RuntimeError('measurement must be 2d')
if measurement.calibrations[0].units != measurement.calibrations[1].units:
raise RuntimeError('the units of the interpolation dimensions must match')
if (gpts is None) & (sampling is None):
sampling = (measurement.calibrations[0].sampling + measurement.calibrations[1].sampling) / 2.
scan = LineScan(start=start, end=end, angle=angle, gpts=gpts, sampling=sampling, margin=margin)
x = np.linspace(measurement.calibrations[0].offset,
measurement.shape[0] * measurement.calibrations[0].sampling +
measurement.calibrations[0].offset,
measurement.shape[0])
y = np.linspace(measurement.calibrations[1].offset,
measurement.shape[1] * measurement.calibrations[1].sampling +
measurement.calibrations[1].offset,
measurement.shape[1])
start = scan.margin_start
end = scan.margin_end
if width is not None:
direction = scan.direction
perpendicular_direction = np.array([-direction[1], direction[0]])
n = int(np.ceil(width / scan.sampling[0]))
perpendicular_positions = np.linspace(-width, width, n)[:, None] * perpendicular_direction[None]
positions = scan.get_positions()[None] + perpendicular_positions[:, None]
positions = positions.reshape((-1, 2))
interpolated_array = interpn((x, y), measurement.array, positions, method=interpolation_method,
bounds_error=False, fill_value=0)
interpolated_array = interpolated_array.reshape((n, -1)).mean(0)
else:
interpolated_array = interpn((x, y), measurement.array, scan.get_positions(), method=interpolation_method,
bounds_error=False, fill_value=0)
return LineProfile(interpolated_array, start=start, end=end,
calibration_units=measurement.calibrations[0].units,
calibration_name=measurement.calibrations[0].name)
def show(self, ax=None, interact=False, **kwargs):
"""
Show the measurement.
Parameters
----------
kwargs:
Additional keyword arguments for the abtem.plot.show_image function.
"""
# TODO : implement interactive show method
if self.dimensions == 1:
return show_measurement_1d(self, ax=ax, **kwargs)
else:
return show_measurement_2d(self, ax=ax, **kwargs)
class LineProfile(AbstractMeasurement):
def __init__(self, array, start=None, end=None, extent=None, endpoint=True, calibration_name='',
calibration_units='', name='', units=''):
if ((start is not None) or (end is not None)) and (extent is not None):
raise ValueError()
if (start is None) != (end is None):
raise ValueError()
self._start = start
self._end = end
self._extent = extent
self._endpoint = endpoint
self._calibration_name = calibration_name
self._calibration_units = calibration_units
super().__init__(array=array, name=name, units=units)
@property
def start(self):
return self._start
@property
def end(self):
return self._end
@property
def extent(self):
if (self._extent is None) & (self._start is not None):
return np.linalg.norm(np.array(self._end) - np.array(self._start), axis=0)
else:
return self._extent
@property
def sampling(self):
return self.extent / self.array.shape[0]
@property
def calibrations(self):
return [Calibration(offset=0, sampling=self.sampling, units=self._calibration_units,
name=self._calibration_name, endpoint=self._endpoint)]
def add_to_mpl_plot(self, ax, **kwargs):
from abtem.scan import LineScan
return LineScan(start=self.start, end=self.end, sampling=self.sampling).add_to_mpl_plot(ax, **kwargs)
def show(self, ax=None, **kwargs):
return show_measurement_1d(self, ax=ax, **kwargs)
def stack_measurements(measurements):
for measurement in measurements[1:]:
for calibration, other_calibration in zip(measurement.calibrations, measurements[0].calibrations):
if calibration != other_calibration:
raise RuntimeError('Measurement calibrations must match.')
for measurement in measurements[1:]:
if measurement.shape != measurements[0].shape:
raise RuntimeError('Measurement shapes must match.')
array = np.stack([measurement.array for measurement in measurements])
calibrations = (None,) + measurements[0].calibrations
return Measurement(array, calibrations=calibrations, units=measurements[0].units, name=measurements[0].name)