forked from hyperspy/hyperspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
axes.py
2420 lines (2086 loc) · 86.7 KB
/
axes.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
# -*- coding: utf-8 -*-
# Copyright 2007-2021 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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.
#
# HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>.
from contextlib import contextmanager
import copy
import math
import logging
import numpy as np
import dask.array as da
import traits.api as t
from traits.trait_errors import TraitError
import pint
from sympy.utilities.lambdify import lambdify
from hyperspy.events import Events, Event
from hyperspy.misc.array_tools import (
numba_closest_index_round,
numba_closest_index_floor,
numba_closest_index_ceil,
round_half_towards_zero,
round_half_away_from_zero,
)
from hyperspy.misc.utils import isiterable, ordinal
from hyperspy.misc.math_tools import isfloat
from hyperspy.ui_registry import add_gui_method, get_gui
from hyperspy.defaults_parser import preferences
from hyperspy._components.expression import _parse_substitutions
import warnings
import inspect
from collections.abc import Iterable
_logger = logging.getLogger(__name__)
_ureg = pint.UnitRegistry()
FACTOR_DOCSTRING = \
"""factor : float (default: 0.25)
'factor' is an adjustable value used to determine the prefix of
the units. The product `factor * scale * size` is passed to the
pint `to_compact` method to determine the prefix."""
class ndindex_nat(np.ndindex):
def __next__(self):
return super(ndindex_nat, self).__next__()[::-1]
def generate_uniform_axis(offset, scale, size, offset_index=0):
"""Creates a uniform axis vector given the offset, scale and number of
channels.
Alternatively, the offset_index of the offset channel can be specified.
Parameters
----------
offset : float
scale : float
size : number of channels
offset_index : int
offset_index number of the offset
Returns
-------
Numpy array
"""
return np.linspace(offset - offset_index * scale,
offset + scale * (size - 1 - offset_index),
size)
def create_axis(**kwargs):
"""Creates a uniform, a non-uniform axis or a functional axis depending on
the kwargs provided. If `axis` or `expression` are provided, a non-uniform
or a functional axis is created, respectively. Otherwise a uniform axis is
created, which can be defined by `scale`, `size` and `offset`.
Alternatively, the offset_index of the offset channel can be specified.
Parameters
----------
axis : iterable of values (list, tuple or 1D numpy array) (optional)
expression : Component function in SymPy text expression format (str) (optional)
offset : float (optional)
scale : float (optional)
size : number of channels (optional)
Returns
-------
A DataAxis, FunctionalDataAxis or a UniformDataAxis
"""
if 'axis' in kwargs.keys(): # non-uniform axis
axis_class = DataAxis
elif 'expression' in kwargs.keys(): # Functional axis
axis_class = FunctionalDataAxis
else: # if not argument is provided fall back to uniform axis
axis_class = UniformDataAxis
return axis_class(**kwargs)
class UnitConversion:
def __init__(self, units=t.Undefined, scale=1.0, offset=0.0):
self.units = units
self.scale = scale
self.offset = units
def _ignore_conversion(self, units):
if units == t.Undefined:
return True
try:
_ureg(units)
except pint.errors.UndefinedUnitError:
warnings.warn('Unit "{}" not supported for conversion. Nothing '
'done.'.format(units),
)
return True
return False
def _convert_compact_units(self, factor=0.25, inplace=True):
""" Convert units to "human-readable" units, which means with a
convenient prefix.
Parameters
----------
%s
"""
if self._ignore_conversion(self.units):
return
scale = self.scale * _ureg(self.units)
scale_size = factor * scale * self.size
converted_units = '{:~}'.format(scale_size.to_compact().units)
return self._convert_units(converted_units, inplace=inplace)
_convert_compact_units.__doc__ %= FACTOR_DOCSTRING
def _get_value_from_value_with_units(self, value):
if self.units is t.Undefined:
raise ValueError("Units conversion can't be perfomed "
f"because the axis '{self}' doesn't have "
"units.")
value = _ureg.parse_expression(value)
if not hasattr(value, 'units'):
raise ValueError(f"`{value}` should contain an units.")
return float(value.to(self.units).magnitude)
def _convert_units(self, converted_units, inplace=True):
if self._ignore_conversion(converted_units) or \
self._ignore_conversion(self.units):
return
scale_pint = self.scale * _ureg(self.units)
offset_pint = self.offset * _ureg(self.units)
scale = float(scale_pint.to(_ureg(converted_units)).magnitude)
offset = float(offset_pint.to(_ureg(converted_units)).magnitude)
units = '{:~}'.format(scale_pint.to(_ureg(converted_units)).units)
if inplace:
self.scale = scale
self.offset = offset
self.units = units
else:
return scale, offset, units
def convert_to_units(self, units=None, inplace=True, factor=0.25):
""" Convert the scale and the units of the current axis. If the unit
of measure is not supported by the pint library, the scale and units
are not modified.
Parameters
----------
units : {str | None}
Default = None
If str, the axis will be converted to the provided units.
If `"auto"`, automatically determine the optimal units to avoid
using too large or too small numbers. This can be tweaked by the
`factor` argument.
inplace : bool
If `True`, convert the axis in place. if `False` return the
`scale`, `offset` and `units`.
%s
"""
if units is None:
out = self._convert_compact_units(factor, inplace=inplace)
else:
out = self._convert_units(units, inplace=inplace)
return out
convert_to_units.__doc__ %= FACTOR_DOCSTRING
def _get_quantity(self, attribute='scale'):
if attribute == 'scale' or attribute == 'offset':
units = self.units
if units == t.Undefined:
units = ''
return getattr(self, attribute) * _ureg(units)
else:
raise ValueError('`attribute` argument can only take the `scale` '
'or the `offset` value.')
def _set_quantity(self, value, attribute='scale'):
if attribute == 'scale' or attribute == 'offset':
units = '' if self.units == t.Undefined else self.units
if isinstance(value, str):
value = _ureg.parse_expression(value)
if isinstance(value, float):
value = value * _ureg(units)
# to be consistent, we also need to convert the other one
# (scale or offset) when both units differ.
if value.units != units and value.units != '' and units != '':
other = 'offset' if attribute == 'scale' else 'scale'
other_quantity = self._get_quantity(other).to(value.units)
setattr(self, other, float(other_quantity.magnitude))
self.units = '{:~}'.format(value.units)
setattr(self, attribute, float(value.magnitude))
else:
raise ValueError('`attribute` argument can only take the `scale` '
'or the `offset` value.')
@property
def units(self):
return self._units
@units.setter
def units(self, s):
if s == '':
self._units = t.Undefined
self._units = s
@add_gui_method(toolkey="hyperspy.DataAxis")
class BaseDataAxis(t.HasTraits):
"""Parent class defining common attributes for all DataAxis classes.
Parameters
----------
name : str, optional
Name string by which the axis can be accessed. `<undefined>` if not set.
units : str, optional
String for the units of the axis vector. `<undefined>` if not set.
navigate : bool, optional
True for a navigation axis. Default False (signal axis).
is_binned : bool, optional
True if data along the axis is binned. Default False.
"""
name = t.Str()
units = t.Str()
size = t.CInt()
low_value = t.Float()
high_value = t.Float()
value = t.Range('low_value', 'high_value')
low_index = t.Int(0)
high_index = t.Int()
slice = t.Instance(slice)
navigate = t.Bool(t.Undefined)
is_binned = t.Bool(t.Undefined)
index = t.Range('low_index', 'high_index')
axis = t.Array()
def __init__(self,
index_in_array=None,
name=t.Undefined,
units=t.Undefined,
navigate=False,
is_binned=False,
**kwargs):
super(BaseDataAxis, self).__init__()
self.events = Events()
if '_type' in kwargs:
_type = kwargs.get('_type')
if _type != self.__class__.__name__:
raise ValueError(f'The passed `_type` ({_type}) of axis is '
'inconsistent with the given attributes.')
_name = self.__class__.__name__
self.events.index_changed = Event("""
Event that triggers when the index of the `{}` changes
Triggers after the internal state of the `{}` has been
updated.
Arguments:
---------
obj : The {} that the event belongs to.
index : The new index
""".format(_name, _name, _name), arguments=["obj", 'index'])
self.events.value_changed = Event("""
Event that triggers when the value of the `{}` changes
Triggers after the internal state of the `{}` has been
updated.
Arguments:
---------
obj : The {} that the event belongs to.
value : The new value
""".format(_name, _name, _name), arguments=["obj", 'value'])
self._suppress_value_changed_trigger = False
self._suppress_update_value = False
self.name = name
self.units = units
self.low_index = 0
self.on_trait_change(self._update_slice, 'navigate')
self.on_trait_change(self.update_index_bounds, 'size')
self.on_trait_change(self._update_bounds, 'axis')
self.index = 0
self.navigate = navigate
self.is_binned = is_binned
self.axes_manager = None
self._is_uniform = False
# The slice must be updated even if the default value did not
# change to correctly set its value.
self._update_slice(self.navigate)
@property
def is_uniform(self):
return self._is_uniform
def _index_changed(self, name, old, new):
self.events.index_changed.trigger(obj=self, index=self.index)
if not self._suppress_update_value:
new_value = self.axis[self.index]
if new_value != self.value:
self.value = new_value
def _value_changed(self, name, old, new):
old_index = self.index
new_index = self.value2index(new)
if old_index != new_index:
self.index = new_index
if new == self.axis[self.index]:
self.events.value_changed.trigger(obj=self, value=new)
elif old_index == new_index:
new_value = self.index2value(new_index)
if new_value == old:
self._suppress_value_changed_trigger = True
try:
self.value = new_value
finally:
self._suppress_value_changed_trigger = False
elif new_value == new and not\
self._suppress_value_changed_trigger:
self.events.value_changed.trigger(obj=self, value=new)
@property
def index_in_array(self):
if self.axes_manager is not None:
return self.axes_manager._axes.index(self)
else:
raise AttributeError(
"This {} does not belong to an AxesManager"
" and therefore its index_in_array attribute "
" is not defined".format(self.__class__.__name__))
@property
def index_in_axes_manager(self):
if self.axes_manager is not None:
return self.axes_manager._get_axes_in_natural_order().\
index(self)
else:
raise AttributeError(
"This {} does not belong to an AxesManager"
" and therefore its index_in_array attribute "
" is not defined".format(self.__class__.__name__))
def _get_positive_index(self, index):
# To be used with re
if index < 0:
index = self.size + index
if index < 0:
raise IndexError("index out of bounds")
return index
def _get_index(self, value):
if isfloat(value):
return self.value2index(value)
else:
return value
def _get_array_slices(self, slice_):
"""Returns a slice to slice the corresponding data axis.
Parameters
----------
slice_ : {float, int, slice}
Returns
-------
my_slice : slice
"""
if isinstance(slice_, slice):
if not self.is_uniform and isfloat(slice_.step):
raise ValueError(
"Float steps are only supported for uniform axes.")
v2i = self.value2index
if isinstance(slice_, slice):
start = slice_.start
stop = slice_.stop
step = slice_.step
else:
if isfloat(slice_):
start = v2i(slice_)
else:
start = self._get_positive_index(slice_)
stop = start + 1
step = None
start = self._parse_value(start)
stop = self._parse_value(stop)
step = self._parse_value(step)
if isfloat(step):
step = int(round(step / self.scale))
if isfloat(start):
try:
start = v2i(start)
except ValueError:
if start > self.high_value:
# The start value is above the axis limit
raise IndexError(
"Start value above axis high bound for axis %s."
"value: %f high_bound: %f" % (repr(self), start,
self.high_value))
else:
# The start value is below the axis limit,
# we slice from the start.
start = None
if isfloat(stop):
try:
stop = v2i(stop)
except ValueError:
if stop < self.low_value:
# The stop value is below the axis limits
raise IndexError(
"Stop value below axis low bound for axis %s."
"value: %f low_bound: %f" % (repr(self), stop,
self.low_value))
else:
# The stop value is below the axis limit,
# we slice until the end.
stop = None
if step == 0:
raise ValueError("slice step cannot be zero")
return slice(start, stop, step)
def _slice_me(self, slice_):
raise NotImplementedError("This method must be implemented by subclasses")
def _get_name(self):
name = (self.name
if self.name is not t.Undefined
else ("Unnamed " +
ordinal(self.index_in_axes_manager))
if self.axes_manager is not None
else "Unnamed")
return name
def __repr__(self):
text = '<%s axis, size: %i' % (self._get_name(),
self.size,)
if self.navigate is True:
text += ", index: %i" % self.index
text += ">"
return text
def __str__(self):
return self._get_name() + " axis"
def update_index_bounds(self):
self.high_index = self.size - 1
def _update_bounds(self):
if len(self.axis) != 0:
self.low_value, self.high_value = (
self.axis.min(), self.axis.max())
def _update_slice(self, value):
if value is False:
self.slice = slice(None)
else:
self.slice = None
def get_axis_dictionary(self):
return {'_type': self.__class__.__name__,
'name': self.name,
'units': self.units,
'navigate': self.navigate,
'is_binned': self.is_binned,
}
def copy(self):
return self.__class__(**self.get_axis_dictionary())
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
cp = self.copy()
return cp
def _parse_value_from_string(self, value):
"""Return calibrated value from a suitable string """
if len(value) == 0:
raise ValueError("Cannot index with an empty string")
# Starting with 'rel', it must be relative slicing
elif value.startswith('rel'):
try:
relative_value = float(value[3:])
except ValueError:
raise ValueError("`rel` must be followed by a number in range [0, 1].")
if relative_value < 0 or relative_value > 1:
raise ValueError("Relative value must be in range [0, 1]")
value = self.low_value + relative_value * (self.high_value - self.low_value)
# if first character is a digit, try unit conversion
# otherwise we don't support it
elif value[0].isdigit():
if self.is_uniform:
value = self._get_value_from_value_with_units(value)
else:
raise ValueError("Unit conversion is only supported for "
"uniform axis.")
else:
raise ValueError(f"`{value}` is not a suitable string for slicing.")
return value
def _parse_value(self, value):
"""Convert the input to calibrated value if string, otherwise,
return the same value."""
if isinstance(value, str):
value = self._parse_value_from_string(value)
elif isinstance(value, (list, tuple, np.ndarray, da.Array)):
value = np.asarray(value)
if value.dtype.type is np.str_:
value = np.array([self._parse_value_from_string(v) for v in value])
return value
def value2index(self, value, rounding=round):
"""Return the closest index/indices to the given value(s) if between the axis limits.
Parameters
----------
value : number or numpy array
rounding : function
Handling of values intermediate between two axis points:
If `rounding=round`, use round-half-away-from-zero strategy to find closest value.
If `rounding=math.floor`, round to the next lower value.
If `round=math.ceil`, round to the next higher value.
Returns
-------
index : integer or numpy array
Raises
------
ValueError
If value is out of bounds or contains out of bounds values (array).
If value is NaN or contains NaN values (array).
"""
if value is None:
return None
else:
value = np.asarray(value)
#Should evaluate on both arrays and scalars. Raises error if there are
#nan values in array
if np.all((value >= self.low_value)*(value <= self.high_value)):
#Only if all values will evaluate correctly do we implement rounding
#function. Rounding functions will strictly operate on numpy arrays
#and only evaluate self.axis - v input, v a scalar within value.
if rounding is round:
#Use argmin(abs) which will return the closest value
# rounding_index = lambda x: np.abs(x).argmin()
index = numba_closest_index_round(self.axis,value).astype(int)
elif rounding is math.ceil:
#Ceiling means finding index of the closest xi with xi - v >= 0
#we look for argmin of strictly non-negative part of self.axis-v.
#The trick is to replace strictly negative values with +np.inf
index = numba_closest_index_ceil(self.axis,value).astype(int)
elif rounding is math.floor:
#flooring means finding index of the closest xi with xi - v <= 0
#we look for armgax of strictly non-positive part of self.axis-v.
#The trick is to replace strictly positive values with -np.inf
index = numba_closest_index_floor(self.axis,value).astype(int)
else:
raise ValueError(
f'Non-supported rounding function. Use '
f'round, math.ceil or math.floor'
)
#initialise the index same dimension as input, force type to int
# index = np.empty_like(value,dtype=int)
#assign on flat, iterate on flat.
# for i,v in enumerate(value):
# index.flat[i] = rounding_index(self.axis - v)
#Squeezing to get a scalar out if scalar in. See squeeze doc
return np.squeeze(index)[()]
else:
raise ValueError(
f'The value {value} is out of the limits '
f'[{self.low_value:.3g}-{self.high_value:.3g}] of the '
f'"{self._get_name()}" axis.'
)
def index2value(self, index):
if isinstance(index, da.Array):
index = index.compute()
if isinstance(index, np.ndarray):
return self.axis[index.ravel()].reshape(index.shape)
else:
return self.axis[index]
def value_range_to_indices(self, v1, v2):
"""Convert the given range to index range.
When a value is out of the axis limits, the endpoint is used instead.
`v1` must be preceding `v2` in the axis values
- if the axis scale is positive, it means v1 < v2
- if the axis scale is negative, it means v1 > v2
Parameters
----------
v1, v2 : float
The end points of the interval in the axis units.
Returns
-------
i2, i2 : float
The indices corresponding to the interval [v1, v2]
"""
i1, i2 = 0, self.size - 1
error_message = "Wrong order of the values: for axis with"
if self._is_increasing_order:
if v1 is not None and v2 is not None and v1 > v2:
raise ValueError(f"{error_message} increasing order, v2 ({v2}) "
f"must be greater than v1 ({v1}).")
if v1 is not None and self.low_value < v1 <= self.high_value:
i1 = self.value2index(v1)
if v2 is not None and self.high_value > v2 >= self.low_value:
i2 = self.value2index(v2)
else:
if v1 is not None and v2 is not None and v1 < v2:
raise ValueError(f"{error_message} decreasing order: v1 ({v1}) "
f"must be greater than v2 ({v2}).")
if v1 is not None and self.high_value > v1 >= self.low_value:
i1 = self.value2index(v1)
if v2 is not None and self.low_value < v2 <= self.high_value:
i2 = self.value2index(v2)
return i1, i2
def update_from(self, axis, attributes):
"""Copy values of specified axes fields from the passed AxesManager.
Parameters
----------
axis : BaseDataAxis
The BaseDataAxis instance to use as a source for values.
attributes : iterable container of strings.
The name of the attribute to update. If the attribute does not
exist in either of the AxesManagers, an AttributeError will be
raised.
Returns
-------
A boolean indicating whether any changes were made.
"""
any_changes = False
changed = {}
for f in attributes:
if getattr(self, f) != getattr(axis, f):
changed[f] = getattr(axis, f)
if len(changed) > 0:
self.trait_set(**changed)
any_changes = True
return any_changes
def convert_to_uniform_axis(self):
scale = (self.high_value - self.low_value) / self.size
d = self.get_axis_dictionary()
axes_manager = self.axes_manager
del d["axis"]
if len(self.axis) > 1:
scale_err = max(self.axis[1:] - self.axis[:-1]) - scale
_logger.warning('The maximum scale error is {}.'.format(scale_err))
d["_type"] = 'UniformDataAxis'
self.__class__ = UniformDataAxis
self.__init__(**d, size=self.size, scale=scale, offset=self.low_value)
self.axes_manager = axes_manager
@property
def _is_increasing_order(self):
"""
Determine if the axis has an increasing, decreasing order or no order
at all.
Returns
-------
True if order is increasing, False if order is decreasing, None
otherwise.
"""
steps = self.axis[1:] - self.axis[:-1]
if np.all(steps > 0):
return True
elif np.all(steps < 0):
return False
else:
# the axis is not ordered
return None
class DataAxis(BaseDataAxis):
"""DataAxis class for a non-uniform axis defined through an ``axis`` array.
The most flexible type of axis, where the axis points are directly given by
an array named ``axis``. As this can be any array, the property
``is_uniform`` is automatically set to ``False``.
Parameters
----------
axis : numpy array or list
The array defining the axis points.
Examples
--------
Sample dictionary for a `DataAxis`:
>>> dict0 = {'axis': np.arange(11)**2}
>>> s = hs.signals.Signal1D(np.ones(12), axes=[dict0])
>>> s.axes_manager[0].get_axis_dictionary()
{'_type': 'DataAxis',
'name': <undefined>,
'units': <undefined>,
'navigate': False,
'axis': array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100])}
"""
def __init__(self,
index_in_array=None,
name=t.Undefined,
units=t.Undefined,
navigate=False,
is_binned=False,
axis=[1],
**kwargs):
super().__init__(
index_in_array=index_in_array,
name=name,
units=units,
navigate=navigate,
is_binned=is_binned,
**kwargs)
self.axis = axis
self.update_axis()
def _slice_me(self, slice_):
"""Returns a slice to slice the corresponding data axis and set the
axis accordingly.
Parameters
----------
slice_ : {int, slice}
Returns
-------
my_slice : slice
"""
my_slice = self._get_array_slices(slice_)
self.axis = self.axis[my_slice]
self.update_axis()
return my_slice
def update_axis(self):
"""Set the value of an axis. The axis values need to be ordered.
Parameters
----------
axis : numpy array or list
Raises
------
ValueError if the axis values are not ordered.
"""
if len(self.axis) > 1:
if isinstance(self.axis, list):
self.axis = np.asarray(self.axis)
if self._is_increasing_order is None:
raise ValueError('The non-uniform axis needs to be ordered.')
self.size = len(self.axis)
def get_axis_dictionary(self):
d = super().get_axis_dictionary()
d.update({'axis': self.axis})
return d
def calibrate(self, *args, **kwargs):
raise TypeError("This function works only for uniform axes.")
def update_from(self, axis, attributes=None):
"""Copy values of specified axes fields from the passed AxesManager.
Parameters
----------
axis : DataAxis
The DataAxis instance to use as a source for values.
attributes : iterable container of strings.
The name of the attribute to update. If the attribute does not
exist in either of the AxesManagers, an AttributeError will be
raised. If `None`, `units` will be updated.
Returns
-------
A boolean indicating whether any changes were made.
"""
if attributes is None:
attributes = ["units"]
return super().update_from(axis, attributes)
def crop(self, start=None, end=None):
"""Crop the axis in place.
Parameters
----------
start : int, float, or None
The beginning of the cropping interval. If type is ``int``,
the value is taken as the axis index. If type is ``float`` the index
is calculated using the axis calibration. If `start`/`end` is
``None`` the method crops from/to the low/high end of the axis.
end : int, float, or None
The end of the cropping interval. If type is ``int``,
the value is taken as the axis index. If type is ``float`` the index
is calculated using the axis calibration. If `start`/`end` is
``None`` the method crops from/to the low/high end of the axis.
"""
slice_ = self._get_array_slices(slice(start, end))
self.axis = self.axis[slice_]
self.size = len(self.axis)
class FunctionalDataAxis(BaseDataAxis):
"""DataAxis class for a non-uniform axis defined through an ``expression``.
A `FunctionalDataAxis` is defined based on an ``expression`` that is
evaluated to yield the axis points. The `expression` is a function defined
as a ``string`` using the `SymPy <https://docs.sympy.org/latest/tutorial/intro.html>`_
text expression format. An example would be ``expression = a / x + b``.
Any variables in the expression, in this case ``a`` and ``b`` must be
defined as additional attributes of the axis. The property ``is_uniform``
is automatically set to ``False``.
``x`` itself is an instance of `BaseDataAxis`. By default, it will be a
`UniformDataAxis` with ``offset = 0`` and ``scale = 1`` of the given
``size``. However, it can also be initialized with custom ``offset`` and
``scale`` values. Alternatively, it can be a non-uniform `DataAxis`.
Parameters
----------
expression: str
SymPy mathematical expression defining the axis.
x : BaseDataAxis
Defines x-values at which `expression` is evaluated.
Examples
--------
Sample dictionary for a FunctionalDataAxis:
>>> dict0 = {'expression': 'a / (x + 1) + b', 'a': 100, 'b': 10, 'size': 500}
>>> s = hs.signals.Signal1D(np.ones(500), axes=[dict0])
>>> s.axes_manager[0].get_axis_dictionary()
{'_type': 'FunctionalDataAxis',
'name': <undefined>,
'units': <undefined>,
'navigate': False,
'expression': 'a / (x + 1) + b',
'size': 500,
'x': {'_type': 'UniformDataAxis',
'name': <undefined>,
'units': <undefined>,
'navigate': <undefined>,
'size': 500,
'scale': 1.0,
'offset': 0.0},
'a': 100,
'b': 10}
"""
def __init__(self,
expression,
x=None,
index_in_array=None,
name=t.Undefined,
units=t.Undefined,
navigate=False,
size=t.Undefined,
is_binned=False,
**parameters):
super().__init__(
index_in_array=index_in_array,
name=name,
units=units,
navigate=navigate,
is_binned=is_binned,
**parameters)
# These trait needs to added dynamically to be removed when necessary
self.add_trait("x", t.Instance(BaseDataAxis))
if x is None:
if size is t.Undefined:
raise ValueError("Please provide either `x` or `size`.")
self.x = UniformDataAxis(scale=1, offset=0, size=size)
else:
if isinstance(x, dict):
self.x = create_axis(**x)
else:
self.x = x
self.size = self.x.size
self._expression = expression
if '_type' in parameters:
del parameters['_type']
# Compile function
expr = _parse_substitutions(self._expression)
variables = ["x"]
expr_parameters = [symbol for symbol in expr.free_symbols
if symbol.name not in variables]
if set(parameters) != set([parameter.name for parameter in expr_parameters]):
raise ValueError(
"The values of the following expression parameters "
f"must be given as keywords: {set(expr_parameters) - set(parameters)}")
self._function = lambdify(
variables + expr_parameters, expr.evalf(), dummify=False)
for parameter in parameters.keys():
self.add_trait(parameter, t.CFloat(parameters[parameter]))
self.parameters_list = list(parameters.keys())
self.update_axis()
self.on_trait_change(self.update_axis, self.parameters_list)
def update_axis(self):
kwargs = {}
for kwarg in self.parameters_list:
kwargs[kwarg] = getattr(self, kwarg)
self.axis = self._function(x=self.x.axis, **kwargs)
# Set not valid values to np.nan
self.axis[np.logical_not(np.isfinite(self.axis))] = np.nan
self.size = len(self.axis)
def update_from(self, axis, attributes=None):
"""Copy values of specified axes fields from the passed AxesManager.
Parameters
----------
axis : FunctionalDataAxis
The FunctionalDataAxis instance to use as a source for values.
attributes : iterable container of strings or None.
A list of the name of the attribute to update. If an attribute does not
exist in either of the AxesManagers, an AttributeError will be
raised. If None, the parameters of `expression` are updated.
Returns
-------
A boolean indicating whether any changes were made.
"""
if attributes is None:
attributes = self.parameters_list
return super().update_from(axis, attributes)