/
utils.py
1413 lines (1182 loc) · 45 KB
/
utils.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 operator import attrgetter
import warnings
import inspect
import copy
import types
from io import StringIO
import codecs
from collections.abc import Iterable, Mapping
import unicodedata
from contextlib import contextmanager
import importlib
import logging
import numpy as np
from hyperspy.misc.signal_tools import broadcast_signals
from hyperspy.exceptions import VisibleDeprecationWarning
from hyperspy.docstrings.signal import SHOW_PROGRESSBAR_ARG
from hyperspy.docstrings.utils import STACK_METADATA_ARG
_logger = logging.getLogger(__name__)
def attrsetter(target, attrs, value):
""" Sets attribute of the target to specified value, supports nested
attributes. Only creates a new attribute if the object supports such
behaviour (e.g. DictionaryTreeBrowser does)
Parameters
----------
target : object
attrs : string
attributes, separated by periods (e.g.
'metadata.Signal.Noise_parameters.variance' )
value : object
Example
-------
First create a signal and model pair:
>>> s = hs.signals.Signal1D(np.arange(10))
>>> m = s.create_model()
>>> m.signal.data
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Now set the data of the model with attrsetter
>>> attrsetter(m, 'signal1D.data', np.arange(10)+2)
>>> self.signal.data
array([2, 3, 4, 5, 6, 7, 8, 9, 10, 10])
The behaviour is identical to
>>> self.signal.data = np.arange(10) + 2
"""
where = attrs.rfind('.')
if where != -1:
target = attrgetter(attrs[:where])(target)
setattr(target, attrs[where + 1:], value)
def generate_axis(origin, step, N, index=0):
"""Creates an axis given the origin, step and number of channels
Alternatively, the index of the origin channel can be specified.
Parameters
----------
origin : float
step : float
N : number of channels
index : int
index of origin
Returns
-------
Numpy array
"""
return np.linspace(
origin - index * step, origin + step * (N - 1 - index), N)
@contextmanager
def stash_active_state(model):
active_state = []
for component in model:
if component.active_is_multidimensional:
active_state.append(component._active_array)
else:
active_state.append(component.active)
yield
for component in model:
active_s = active_state.pop(0)
if isinstance(active_s, bool):
component.active = active_s
else:
if not component.active_is_multidimensional:
component.active_is_multidimensional = True
component._active_array[:] = active_s
@contextmanager
def dummy_context_manager(*args, **kwargs):
yield
def str2num(string, **kargs):
"""Transform a a table in string form into a numpy array
Parameters
----------
string : string
Returns
-------
numpy array
"""
stringIO = StringIO(string)
return np.loadtxt(stringIO, **kargs)
def parse_quantity(quantity, opening='(', closing=')'):
"""Parse quantity of the signal outputting quantity and units separately.
It looks for the last matching opening and closing separator.
Parameters
----------
quantity : string
opening : string
Separator used to define the beginning of the units
closing : string
Separator used to define the end of the units
Returns
-------
quantity_name : string
quantity_units : string
"""
# open_bracket keep track of the currently open brackets
open_bracket = 0
for index, c in enumerate(quantity.strip()[::-1]):
if c == closing:
# we find an closing, increment open_bracket
open_bracket += 1
if c == opening:
# we find a opening, decrement open_bracket
open_bracket -= 1
if open_bracket == 0:
# we found the matching bracket and we will use the index
break
if index + 1 == len(quantity):
return quantity, ""
else:
quantity_name = quantity[:-index-1].strip()
quantity_units = quantity[-index:-1].strip()
return quantity_name, quantity_units
_slugify_strip_re_data = ''.join(
c for c in map(
chr, np.delete(
np.arange(256), [
95, 32])) if not c.isalnum()).encode()
def slugify(value, valid_variable_name=False):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Adapted from Django's "django/template/defaultfilters.py".
"""
if not isinstance(value, str):
try:
# Convert to unicode using the default encoding
value = str(value)
except BaseException:
# Try latin1. If this does not work an exception is raised.
value = str(value, "latin1")
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = value.translate(None, _slugify_strip_re_data).decode().strip()
value = value.replace(' ', '_')
if valid_variable_name and not value.isidentifier():
value = 'Number_' + value
return value
class DictionaryTreeBrowser:
"""A class to comfortably browse a dictionary using a CLI.
In addition to accessing the values using dictionary syntax
the class enables navigating a dictionary that constains
nested dictionaries as attribures of nested classes.
Also it is an iterator over the (key, value) items. The
`__repr__` method provides pretty tree printing. Private
keys, i.e. keys that starts with an underscore, are not
printed, counted when calling len nor iterated.
Methods
-------
export : saves the dictionary in pretty tree printing format in a text
file.
keys : returns a list of non-private keys.
as_dictionary : returns a dictionary representation of the object.
set_item : easily set items, creating any necessary node on the way.
add_node : adds a node.
Examples
--------
>>> tree = DictionaryTreeBrowser()
>>> tree.set_item("Branch.Leaf1.color", "green")
>>> tree.set_item("Branch.Leaf2.color", "brown")
>>> tree.set_item("Branch.Leaf2.caterpillar", True)
>>> tree.set_item("Branch.Leaf1.caterpillar", False)
>>> tree
└── Branch
├── Leaf1
│ ├── caterpillar = False
│ └── color = green
└── Leaf2
├── caterpillar = True
└── color = brown
>>> tree.Branch
├── Leaf1
│ ├── caterpillar = False
│ └── color = green
└── Leaf2
├── caterpillar = True
└── color = brown
>>> for label, leaf in tree.Branch:
... print("%s is %s" % (label, leaf.color))
Leaf1 is green
Leaf2 is brown
>>> tree.Branch.Leaf2.caterpillar
True
>>> "Leaf1" in tree.Branch
True
>>> "Leaf3" in tree.Branch
False
>>>
"""
def __init__(self, dictionary=None, double_lines=False, lazy=True):
"""When creating a DictionaryTreeBrowser lazily, the dictionary is
added to the `_lazy_attributes` attribute. The first time a lazy
attribute is called or the DictionaryTreeBrowser is printed, the
DictionaryTreeBrowser processes the lazy attributes with the
`process_lazy_attributes` method.
DictionaryTreeBrowser is lazy by default, using non-lazy instances
can be useful for debugging purposes.
"""
self._lazy_attributes = {}
self._double_lines = double_lines
if dictionary is None:
dictionary = {}
if lazy:
self._lazy_attributes.update(dictionary)
else:
self._process_dictionary(dictionary, double_lines)
def _process_dictionary(self, dictionary, double_lines):
"""Process the provided dictionary to set the attributes
"""
for key, value in dictionary.items():
if key == '_double_lines':
value = double_lines
self.__setattr__(key, value)
def process_lazy_attributes(self):
"""Run the DictionaryTreeBrowser machinery for the lazy attributes.
"""
if len(self._lazy_attributes) > 0:
_logger.debug("Processing lazy attributes DictionaryBrowserTree")
self._process_dictionary(self._lazy_attributes, self._double_lines)
self._lazy_attributes = {}
def add_dictionary(self, dictionary, double_lines=False):
"""Add new items from dictionary.
"""
if len(self._lazy_attributes) > 0:
# To simplify merging lazy and non lazy attribute, we get self
# as a dictionary and update the dictionary with the attributes
d = self.as_dictionary()
nested_dictionary_merge(d, dictionary)
self.__init__(d, double_lines=double_lines, lazy=True)
else:
self._process_dictionary(dictionary, double_lines)
def export(self, filename, encoding='utf8'):
"""Export the dictionary to a text file
Parameters
----------
filename : str
The name of the file without the extension that is
txt by default
encoding : valid encoding str
"""
f = codecs.open(filename, 'w', encoding=encoding)
f.write(self._get_print_items(max_len=None))
f.close()
def _get_print_items(self, padding='', max_len=78):
"""Prints only the attributes that are not methods
"""
from hyperspy.defaults_parser import preferences
string = ''
eoi = len(self)
j = 0
if preferences.General.dtb_expand_structures and self._double_lines:
s_end = '╚══ '
s_middle = '╠══ '
pad_middle = '║ '
else:
s_end = '└── '
s_middle = '├── '
pad_middle = '│ '
for key_, value in iter(sorted(self.__dict__.items())):
if key_.startswith("_"):
continue
if not isinstance(key_, types.MethodType):
key = ensure_unicode(value['key'])
value = value['_dtb_value_']
if j == eoi - 1:
symbol = s_end
else:
symbol = s_middle
if preferences.General.dtb_expand_structures:
if isinstance(value, list) or isinstance(value, tuple):
iflong, strvalue = check_long_string(value, max_len)
if iflong:
key += (" <list>"
if isinstance(value, list)
else " <tuple>")
value = DictionaryTreeBrowser(
{'[%d]' % i: v for i, v in enumerate(value)},
double_lines=True,
lazy=False)
else:
string += "%s%s%s = %s\n" % (
padding, symbol, key, strvalue)
j += 1
continue
if isinstance(value, DictionaryTreeBrowser):
string += '%s%s%s\n' % (padding, symbol, key)
if j == eoi - 1:
extra_padding = ' '
else:
extra_padding = pad_middle
string += value._get_print_items(
padding + extra_padding)
else:
_, strvalue = check_long_string(value, max_len)
string += "%s%s%s = %s\n" % (
padding, symbol, key, strvalue)
j += 1
return string
def _get_html_print_items(self, padding='', max_len=78, recursive_level=0):
"""Recursive method that creates a html string for fancy display
of metadata.
"""
recursive_level += 1
from hyperspy.defaults_parser import preferences
string = '' # Final return string
for key_, value in iter(sorted(self.__dict__.items())):
if key_.startswith("_"): # Skip any private attributes
continue
if not isinstance(key_, types.MethodType): # If it isn't a method, then continue
key = ensure_unicode(value['key'])
value = value['_dtb_value_']
# dtb_expand_structures is a setting that sets whether to fully expand long strings
if preferences.General.dtb_expand_structures:
if isinstance(value, list) or isinstance(value, tuple):
iflong, strvalue = check_long_string(value, max_len)
if iflong:
key += (" <list>"
if isinstance(value, list)
else " <tuple>")
value = DictionaryTreeBrowser(
{'[%d]' % i: v for i, v in enumerate(value)},
double_lines=True,
lazy=False)
else:
string += add_key_value(key, strvalue)
continue # skips the next if-else
# If DTB, then add a details html tag
if isinstance(value, DictionaryTreeBrowser):
string += """<ul style="margin: 0px; list-style-position: outside;">
<details {}>
<summary style="display: list-item;">
<li style="display: inline;">
{}
</li></summary>
""".format("open" if recursive_level < 2 else "closed", replace_html_symbols(key))
string += value._get_html_print_items(recursive_level=recursive_level)
string += '</details></ul>'
# Otherwise just add value
else:
_, strvalue = check_long_string(value, max_len)
string += add_key_value(key, strvalue)
return string
def __repr__(self):
self.process_lazy_attributes()
return self._get_print_items()
def _repr_html_(self):
self.process_lazy_attributes()
return self._get_html_print_items()
def __getitem__(self, key):
self.process_lazy_attributes()
return self.__getattribute__(key)
def __setitem__(self, key, value):
self.__setattr__(key, value)
def __getattr__(self, name):
"""__getattr__ is called when the default attribute access (
__getattribute__) fails with an AttributeError.
"""
# Skip the attribute we are not interested in. This is also necessary
# to recursive loops.
if name.startswith("__"):
raise AttributeError(name)
# Attribute name are been slugified, so we need to do the same for
# the dictionary keys. Also check with `_sig_` prefix for signal attributes.
keys = [slugify(k) for k in self._lazy_attributes.keys()]
if name in keys or f"_sig_{name}" in keys:
# It is a lazy attribute, we need to process the lazy attribute
self.process_lazy_attributes()
return self.__dict__[name]['_dtb_value_']
else:
raise AttributeError(name)
def __getattribute__(self, name):
if isinstance(name, bytes):
name = name.decode()
name = slugify(name, valid_variable_name=True)
item = super().__getattribute__(name)
if isinstance(item, dict) and '_dtb_value_' in item and "key" in item:
return item['_dtb_value_']
else:
return item
def __setattr__(self, key, value):
if key in ['_double_lines', '_lazy_attributes']:
super().__setattr__(key, value)
return
if key.startswith('_sig_'):
key = key[5:]
from hyperspy.signal import BaseSignal
value = BaseSignal(**value)
slugified_key = str(slugify(key, valid_variable_name=True))
if isinstance(value, dict):
if slugified_key in self.__dict__.keys():
self.__dict__[slugified_key]['_dtb_value_'].add_dictionary(
value,
double_lines=self._double_lines)
return
else:
value = DictionaryTreeBrowser(
value,
double_lines=self._double_lines,
lazy=False)
super().__setattr__(slugified_key, {'key': key, '_dtb_value_': value})
def __len__(self):
if len(self._lazy_attributes) > 0:
d = self._lazy_attributes
else:
d = self.__dict__
return len([key for key in d.keys() if not key.startswith("_")])
def keys(self):
"""Returns a list of non-private keys.
"""
return sorted([key for key in self.__dict__.keys()
if not key.startswith("_")])
def as_dictionary(self):
"""Returns its dictionary representation.
"""
if len(self._lazy_attributes) > 0:
return copy.deepcopy(self._lazy_attributes)
par_dict = {}
from hyperspy.signal import BaseSignal
for key_, item_ in self.__dict__.items():
if not isinstance(item_, types.MethodType):
if key_ in ["_db_index", "_double_lines", "_lazy_attributes"]:
continue
key = item_['key']
if isinstance(item_['_dtb_value_'], DictionaryTreeBrowser):
item = item_['_dtb_value_'].as_dictionary()
elif isinstance(item_['_dtb_value_'], BaseSignal):
item = item_['_dtb_value_']._to_dictionary()
key = '_sig_' + key
elif hasattr(item_['_dtb_value_'], '_to_dictionary'):
item = item_['_dtb_value_']._to_dictionary()
else:
item = item_['_dtb_value_']
par_dict.update({key:item})
return par_dict
def has_item(self, item_path):
"""Given a path, return True if it exists.
The nodes of the path are separated using periods.
Parameters
----------
item_path : Str
A string describing the path with each item separated by
full stops (periods)
Examples
--------
>>> dict = {'To' : {'be' : True}}
>>> dict_browser = DictionaryTreeBrowser(dict)
>>> dict_browser.has_item('To')
True
>>> dict_browser.has_item('To.be')
True
>>> dict_browser.has_item('To.be.or')
False
"""
if isinstance(item_path, str):
item_path = item_path.split('.')
else:
item_path = copy.copy(item_path)
attrib = item_path.pop(0)
if hasattr(self, attrib):
if len(item_path) == 0:
return True
else:
item = self[attrib]
if isinstance(item, type(self)):
return item.has_item(item_path)
else:
return False
else:
return False
def get_item(self, item_path, default=None):
"""Given a path, return it's value if it exists, or default
value if missing.
The nodes of the path are separated using periods.
Parameters
----------
item_path : Str
A string describing the path with each item separated by
full stops (periods)
default :
The value to return if the path does not exist.
Examples
--------
>>> dict = {'To' : {'be' : True}}
>>> dict_browser = DictionaryTreeBrowser(dict)
>>> dict_browser.get_item('To')
└── be = True
>>> dict_browser.get_item('To.be')
True
>>> dict_browser.get_item('To.be.or', 'default_value')
'default_value'
"""
if isinstance(item_path, str):
item_path = item_path.split('.')
else:
item_path = copy.copy(item_path)
attrib = item_path.pop(0)
if hasattr(self, attrib):
if len(item_path) == 0:
return self[attrib]
else:
item = self[attrib]
if isinstance(item, type(self)):
return item.get_item(item_path, default)
else:
return default
else:
return default
def __contains__(self, item):
return self.has_item(item_path=item)
def copy(self):
return copy.copy(self)
def deepcopy(self):
return copy.deepcopy(self)
def set_item(self, item_path, value):
"""Given the path and value, create the missing nodes in
the path and assign to the last one the value
Parameters
----------
item_path : Str
A string describing the path with each item separated by a
full stops (periods)
Examples
--------
>>> dict_browser = DictionaryTreeBrowser({})
>>> dict_browser.set_item('First.Second.Third', 3)
>>> dict_browser
└── First
└── Second
└── Third = 3
"""
if not self.has_item(item_path):
self.add_node(item_path)
if isinstance(item_path, str):
item_path = item_path.split('.')
if len(item_path) > 1:
self.__getattribute__(item_path.pop(0)).set_item(
item_path, value)
else:
self.__setattr__(item_path.pop(), value)
def add_node(self, node_path):
"""Adds all the nodes in the given path if they don't exist.
Parameters
----------
node_path: str
The nodes must be separated by full stops (periods).
Examples
--------
>>> dict_browser = DictionaryTreeBrowser({})
>>> dict_browser.add_node('First.Second')
>>> dict_browser.First.Second = 3
>>> dict_browser
└── First
└── Second = 3
"""
keys = node_path.split('.')
dtb = self
for key in keys:
if dtb.has_item(key) is False:
dtb[key] = DictionaryTreeBrowser(lazy=False)
dtb = dtb[key]
def __next__(self):
"""
Standard iterator method, updates the index and returns the
current coordiantes
Returns
-------
val : tuple of ints
Returns a tuple containing the coordiantes of the current
iteration.
"""
if len(self) == 0:
raise StopIteration
if not hasattr(self, '_db_index'):
self._db_index = 0
elif self._db_index >= len(self) - 1:
del self._db_index
raise StopIteration
else:
self._db_index += 1
self.process_lazy_attributes()
key = list(self.keys())[self._db_index]
return key, getattr(self, key)
def __iter__(self):
return self
def strlist2enumeration(lst):
lst = tuple(lst)
if not lst:
return ''
elif len(lst) == 1:
return lst[0]
elif len(lst) == 2:
return "%s and %s" % lst
else:
return "%s, " * (len(lst) - 2) % lst[:-2] + "%s and %s" % lst[-2:]
def ensure_unicode(stuff, encoding='utf8', encoding2='latin-1'):
if not isinstance(stuff, (bytes, np.string_)):
return stuff
else:
string = stuff
try:
string = string.decode(encoding)
except BaseException:
string = string.decode(encoding2, errors='ignore')
return string
def check_long_string(value, max_len):
"Checks whether string is too long for printing in html metadata"
if not isinstance(value, (str, np.string_)):
value = repr(value)
value = ensure_unicode(value)
strvalue = str(value)
_long = False
if max_len is not None and len(strvalue) > 2 * max_len:
right_limit = min(max_len, len(strvalue) - max_len)
strvalue = '%s ... %s' % (
strvalue[:max_len], strvalue[-right_limit:])
_long = True
return _long, strvalue
def replace_html_symbols(str_value):
"Escapes any &, < and > tags that would become invisible when printing html"
str_value = str_value.replace("&", "&")
str_value = str_value.replace("<", "<")
str_value = str_value.replace(">", ">")
return str_value
def add_key_value(key, value):
"Returns the metadata value as a html string"
return """
<ul style="margin: 0px; list-style-position: outside;">
<li style='margin-left:1em; padding-left: 0.5em'>{} = {}</li></ul>
""".format(replace_html_symbols(key), replace_html_symbols(value))
def swapelem(obj, i, j):
"""Swaps element having index i with element having index j in object obj
IN PLACE.
Example
-------
>>> L = ['a', 'b', 'c']
>>> spwapelem(L, 1, 2)
>>> print(L)
['a', 'c', 'b']
"""
if len(obj) > 1:
buf = obj[i]
obj[i] = obj[j]
obj[j] = buf
def rollelem(a, index, to_index=0):
"""Roll the specified axis backwards, until it lies in a given position.
Parameters
----------
a : list
Input list.
index : int
The index of the item to roll backwards. The positions of the items
do not change relative to one another.
to_index : int, optional
The item is rolled until it lies before this position. The default,
0, results in a "complete" roll.
Returns
-------
res : list
Output list.
"""
res = copy.copy(a)
res.insert(to_index, res.pop(index))
return res
def fsdict(nodes, value, dictionary):
"""Populates the dictionary 'dic' in a file system-like
fashion creating a dictionary of dictionaries from the
items present in the list 'nodes' and assigning the value
'value' to the innermost dictionary.
'dic' will be of the type:
dic['node1']['node2']['node3']...['nodeN'] = value
where each node is like a directory that contains other
directories (nodes) or files (values)
"""
node = nodes.pop(0)
if node not in dictionary:
dictionary[node] = {}
if len(nodes) != 0 and isinstance(dictionary[node], dict):
fsdict(nodes, value, dictionary[node])
else:
dictionary[node] = value
def find_subclasses(mod, cls):
"""Find all the subclasses in a module.
Parameters
----------
mod : module
cls : class
Returns
-------
dictonary in which key, item = subclass name, subclass
"""
return dict([(name, obj) for name, obj in inspect.getmembers(mod)
if inspect.isclass(obj) and issubclass(obj, cls)])
def isiterable(obj):
return isinstance(obj, Iterable)
def ordinal(value):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
'1st'
'2nd'
'3rd'
'4th'
'5th'
'6th'
'7th'
'8th'
'9th'
'10th'
'11th'
'12th'
>>> for i in (100, '111', '112',1011):
... ordinal(i)
...
'100th'
'111th'
'112th'
'1011th'
Notes
-----
Author: Serdar Tumgoren
http://code.activestate.com/recipes/576888-format-a-number-as-an-ordinal/
MIT license
"""
try:
value = int(value)
except ValueError:
return value
if value % 100 // 10 != 1:
if value % 10 == 1:
ordval = "%d%s" % (value, "st")
elif value % 10 == 2:
ordval = "%d%s" % (value, "nd")
elif value % 10 == 3:
ordval = "%d%s" % (value, "rd")
else:
ordval = "%d%s" % (value, "th")
else:
ordval = "%d%s" % (value, "th")
return ordval
def underline(line, character="-"):
"""Return the line underlined.
"""
return line + "\n" + character * len(line)
def closest_power_of_two(n):
return int(2 ** np.ceil(np.log2(n)))
def stack(signal_list, axis=None, new_axis_name="stack_element", lazy=None,
stack_metadata=True, show_progressbar=None, **kwargs):
"""Concatenate the signals in the list over a given axis or a new axis.
The title is set to that of the first signal in the list.
Parameters
----------
signal_list : list of BaseSignal instances
List of signals to stack.
axis : {None, int, str}
If None, the signals are stacked over a new axis. The data must
have the same dimensions. Otherwise the
signals are stacked over the axis given by its integer index or
its name. The data must have the same shape, except in the dimension
corresponding to `axis`.
new_axis_name : str
The name of the new axis when `axis` is None.
If an axis with this name already
exists it automatically append '-i', where `i` are integers,
until it finds a name that is not yet in use.
lazy : {bool, None}
Returns a LazySignal if True. If None, only returns lazy result if at
least one is lazy.
%s
%s
Returns
-------
signal : BaseSignal instance
Examples
--------
>>> data = np.arange(20)
>>> s = hs.stack([hs.signals.Signal1D(data[:10]),
... hs.signals.Signal1D(data[10:])])
>>> s
<Signal1D, title: Stack of , dimensions: (2, 10)>
>>> s.data
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
"""
from hyperspy.signals import BaseSignal
import dask.array as da
from numbers import Number
for k in [k for k in ["mmap", "mmap_dir"] if k in kwargs]:
lazy = True
warnings.warn(
f"'{k}' argument is deprecated and will be removed in "
"HyperSpy v2.0. Please use 'lazy=True' instead.",
VisibleDeprecationWarning,
)
axis_input = copy.deepcopy(axis)
signal_list = list(signal_list)
# Get the real signal with the most axes to get metadata/class/etc
# first = sorted(filter(lambda _s: isinstance(_s, BaseSignal), signal_list),
# key=lambda _s: _s.data.ndim)[-1]
first = next(filter(lambda _s: isinstance(_s, BaseSignal), signal_list))
# Cast numbers as signals. Will broadcast later.