-
Notifications
You must be signed in to change notification settings - Fork 207
/
signal.py
6635 lines (5841 loc) · 260 KB
/
signal.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-2023 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 <https://www.gnu.org/licenses/#GPL>.
from collections.abc import MutableMapping
from contextlib import contextmanager
import copy
from datetime import datetime
from functools import partial
import inspect
from itertools import product
import logging
import numbers
from pathlib import Path
import warnings
import dask.array as da
from dask.diagnostics import ProgressBar
from matplotlib import pyplot as plt
import numpy as np
from pint import UndefinedUnitError
from scipy import integrate
from scipy import signal as sp_signal
import traits.api as t
from tlz import concat
from rsciio.utils import rgb_tools
from rsciio.utils.tools import ensure_directory
from hyperspy.axes import AxesManager
from hyperspy.api_nogui import _ureg
from hyperspy.misc.array_tools import rebin as array_rebin
from hyperspy.drawing import mpl_hie, mpl_hse, mpl_he
from hyperspy.learn.mva import MVA, LearningResults
from hyperspy.io import assign_signal_subclass
from hyperspy.io import save as io_save
from hyperspy.drawing import signal as sigdraw
from hyperspy.exceptions import SignalDimensionError, DataDimensionError
from hyperspy.misc.utils import (
add_scalar_axis,
DictionaryTreeBrowser,
guess_output_signal_size,
is_cupy_array,
isiterable,
iterable_not_string,
process_function_blockwise,
rollelem,
slugify,
to_numpy,
underline,
)
from hyperspy.misc.hist_tools import histogram
from hyperspy.drawing.utils import animate_legend
from hyperspy.drawing.marker import markers_metadata_dict_to_markers
from hyperspy.misc.slicing import SpecialSlicers, FancySlicing
from hyperspy.misc.utils import _get_block_pattern
from hyperspy.docstrings.signal import (
ONE_AXIS_PARAMETER, MANY_AXIS_PARAMETER, OUT_ARG, NAN_FUNC, OPTIMIZE_ARG,
RECHUNK_ARG, SHOW_PROGRESSBAR_ARG, NUM_WORKERS_ARG,
CLUSTER_SIGNALS_ARG, HISTOGRAM_BIN_ARGS, HISTOGRAM_MAX_BIN_ARGS, LAZY_OUTPUT_ARG)
from hyperspy.docstrings.plot import (BASE_PLOT_DOCSTRING, PLOT1D_DOCSTRING,
BASE_PLOT_DOCSTRING_PARAMETERS,
PLOT2D_KWARGS_DOCSTRING)
from hyperspy.docstrings.utils import REBIN_ARGS
from hyperspy.events import Events, Event
from hyperspy.interactive import interactive
from hyperspy.misc.signal_tools import are_signals_aligned, broadcast_signals
from hyperspy.misc.math_tools import outer_nd, hann_window_nth_order, check_random_state
from hyperspy.exceptions import LazyCupyConversion
_logger = logging.getLogger(__name__)
try:
import cupy as cp
CUPY_INSTALLED = True # pragma: no cover
except ImportError:
CUPY_INSTALLED = False
def _dic_get_hs_obj_paths(dic, axes_managers, signals, containers):
for key in dic:
if key.startswith('_sig_'):
signals.append((key, dic))
elif key.startswith('_hspy_AxesManager_'):
axes_managers.append((key, dic))
elif isinstance(dic[key], (list, tuple)):
signals = []
# Support storing signals in containers
for i, item in enumerate(dic[key]):
if isinstance(item, dict) and "_sig_" in item:
signals.append(i)
if signals:
containers.append(((dic, key), signals))
elif isinstance(dic[key], dict):
_dic_get_hs_obj_paths(
dic[key],
axes_managers=axes_managers,
signals=signals,
containers=containers
)
def _obj_in_dict2hspy(dic, lazy):
"""
Recursively walk nested dicts substituting dicts with their hyperspy
object where relevant
Parameters
----------
d: dictionary
The nested dictionary
lazy: bool
"""
from hyperspy.io import dict2signal
axes_managers, signals, containers = [], [], []
_dic_get_hs_obj_paths(
dic,
axes_managers=axes_managers,
signals=signals,
containers=containers
)
for key, dic in axes_managers:
dic[key[len('_hspy_AxesManager_'):]] = AxesManager(dic[key])
del dic[key]
for key, dic in signals:
dic[key[len('_sig_'):]] = dict2signal(dic[key], lazy=lazy)
del dic[key]
for dickey, signals_idx in containers:
dic, key = dickey
container = dic[key]
to_tuple = False
if type(container) is tuple:
container = list(container)
to_tuple = True
for idx in signals_idx:
container[idx] = dict2signal(container[idx]["_sig_"], lazy=lazy)
if to_tuple:
dic[key] = tuple(container)
class ModelManager(object):
"""Container for models
"""
class ModelStub(object):
def __init__(self, mm, name):
self._name = name
self._mm = mm
self.restore = lambda: mm.restore(self._name)
self.remove = lambda: mm.remove(self._name)
self.pop = lambda: mm.pop(self._name)
self.restore.__doc__ = "Returns the stored model"
self.remove.__doc__ = "Removes the stored model"
self.pop.__doc__ = \
"Returns the stored model and removes it from storage"
def __repr__(self):
return repr(self._mm._models[self._name])
def __init__(self, signal, dictionary=None):
self._signal = signal
self._models = DictionaryTreeBrowser()
self._add_dictionary(dictionary)
def _add_dictionary(self, dictionary=None):
if dictionary is not None:
for k, v in dictionary.items():
if k.startswith('_') or k in ['restore', 'remove']:
raise KeyError("Can't add dictionary with key '%s'" % k)
k = slugify(k, True)
self._models.set_item(k, v)
setattr(self, k, self.ModelStub(self, k))
def _set_nice_description(self, node, names):
ans = {'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'dimensions': self._signal.axes_manager._get_dimension_str(),
}
node.add_dictionary(ans)
for n in names:
node.add_node('components.' + n)
def _save(self, name, dictionary):
_abc = 'abcdefghijklmnopqrstuvwxyz'
def get_letter(models):
howmany = len(models)
if not howmany:
return 'a'
order = int(np.log(howmany) / np.log(26)) + 1
letters = [_abc, ] * order
for comb in product(*letters):
guess = "".join(comb)
if guess not in models.keys():
return guess
if name is None:
name = get_letter(self._models)
else:
name = self._check_name(name)
if name in self._models:
self.remove(name)
self._models.add_node(name)
node = self._models.get_item(name)
names = [c['name'] for c in dictionary['components']]
self._set_nice_description(node, names)
node.set_item('_dict', dictionary)
setattr(self, name, self.ModelStub(self, name))
def store(self, model, name=None):
"""If the given model was created from this signal, stores it
Parameters
----------
model : :py:class:`~hyperspy.model.BaseModel` (or subclass)
The model to store in the signal
name : str or None
The name for the model to be stored with
See also
--------
remove
restore
pop
"""
if model.signal is self._signal:
self._save(name, model.as_dictionary())
else:
raise ValueError("The model is created from a different signal, "
"you should store it there")
def _check_name(self, name, existing=False):
if not isinstance(name, str):
raise KeyError('Name has to be a string')
if name.startswith('_'):
raise KeyError('Name cannot start with "_" symbol')
if '.' in name:
raise KeyError('Name cannot contain dots (".")')
name = slugify(name, True)
if existing:
if name not in self._models:
raise KeyError(
"Model named '%s' is not currently stored" %
name)
return name
def remove(self, name):
"""Removes the given model
Parameters
----------
name : str
The name of the model to remove
See also
--------
restore
store
pop
"""
name = self._check_name(name, True)
delattr(self, name)
self._models.__delattr__(name)
def pop(self, name):
"""Returns the restored model and removes it from storage
Parameters
----------
name : str
The name of the model to restore and remove
See also
--------
restore
store
remove
"""
name = self._check_name(name, True)
model = self.restore(name)
self.remove(name)
return model
def restore(self, name):
"""Returns the restored model
Parameters
----------
name : str
The name of the model to restore
See also
--------
remove
store
pop
"""
name = self._check_name(name, True)
d = self._models.get_item(name + '._dict').as_dictionary()
return self._signal.create_model(dictionary=copy.deepcopy(d))
def __repr__(self):
return repr(self._models)
def __len__(self):
return len(self._models)
def __getitem__(self, name):
name = self._check_name(name, True)
return getattr(self, name)
class MVATools(object):
# TODO: All of the plotting methods here should move to drawing
def _plot_factors_or_pchars(self, factors, comp_ids=None,
calibrate=True, avg_char=False,
same_window=True, comp_label='PC',
img_data=None,
plot_shifts=True, plot_char=4,
cmap=plt.cm.gray, quiver_color='white',
vector_scale=1,
per_row=3, ax=None):
"""Plot components from PCA or ICA, or peak characteristics.
Parameters
----------
comp_ids : None, int, or list of ints
If None, returns maps of all components.
If int, returns maps of components with ids from 0 to given
int.
if list of ints, returns maps of components with ids in
given list.
calibrate : bool
If True, plots are calibrated according to the data in the
axes manager.
same_window : bool
If True, plots each factor to the same window. They are not scaled.
Default True.
comp_label : str
Title of the plot
cmap : a matplotlib colormap
The colormap used for factor images or any peak characteristic
scatter map overlay. Default is the matplotlib gray colormap
(``plt.cm.gray``).
Other Parameters
----------------
img_data : 2D numpy array,
The array to overlay peak characteristics onto. If None,
defaults to the average image of your stack.
plot_shifts : bool, default is True
If true, plots a quiver (arrow) plot showing the shifts for
each
peak present in the component being plotted.
plot_char : None or int
If int, the id of the characteristic to plot as the colored
scatter plot.
Possible components are:
* 4: peak height
* 5: peak orientation
* 6: peak eccentricity
quiver_color : any color recognized by matplotlib
Determines the color of vectors drawn for
plotting peak shifts.
vector_scale : integer or None
Scales the quiver plot arrows. The vector is defined as one data
unit along the X axis. If shifts are small, set vector_scale so
that when they are multiplied by vector_scale, they are on the
scale of the image plot. If None, uses matplotlib's autoscaling.
Returns
-------
matplotlib figure or list of figure if same_window=False
"""
if same_window is None:
same_window = True
if comp_ids is None:
comp_ids = range(factors.shape[1])
elif not hasattr(comp_ids, '__iter__'):
comp_ids = range(comp_ids)
n = len(comp_ids)
if same_window:
rows = int(np.ceil(n / float(per_row)))
fig_list = []
if n < per_row:
per_row = n
if same_window and self.axes_manager.signal_dimension == 2:
f = plt.figure(figsize=(4 * per_row, 3 * rows))
else:
f = plt.figure()
for i in range(len(comp_ids)):
if self.axes_manager.signal_dimension == 1:
if same_window:
ax = plt.gca()
else:
if i > 0:
f = plt.figure()
plt.title('%s' % comp_label)
ax = f.add_subplot(111)
ax = sigdraw._plot_1D_component(
factors=factors,
idx=comp_ids[i],
axes_manager=self.axes_manager,
ax=ax,
calibrate=calibrate,
comp_label=comp_label,
same_window=same_window)
if same_window:
plt.legend(ncol=factors.shape[1] // 2, loc='best')
elif self.axes_manager.signal_dimension == 2:
if same_window:
ax = f.add_subplot(rows, per_row, i + 1)
else:
if i > 0:
f = plt.figure()
plt.title('%s' % comp_label)
ax = f.add_subplot(111)
sigdraw._plot_2D_component(factors=factors,
idx=comp_ids[i],
axes_manager=self.axes_manager,
calibrate=calibrate, ax=ax,
cmap=cmap, comp_label=comp_label)
if not same_window:
fig_list.append(f)
if same_window: # Main title for same window
title = '%s' % comp_label
if self.axes_manager.signal_dimension == 1:
plt.title(title)
else:
plt.suptitle(title)
try:
plt.tight_layout()
except BaseException:
pass
if not same_window:
return fig_list
else:
return f
def _plot_loadings(self, loadings, comp_ids, calibrate=True,
same_window=True, comp_label=None,
with_factors=False, factors=None,
cmap=plt.cm.gray, no_nans=False, per_row=3,
axes_decor='all'):
if same_window is None:
same_window = True
if comp_ids is None:
comp_ids = range(loadings.shape[0])
elif not hasattr(comp_ids, '__iter__'):
comp_ids = range(comp_ids)
n = len(comp_ids)
if same_window:
rows = int(np.ceil(n / float(per_row)))
fig_list = []
if n < per_row:
per_row = n
if same_window and self.axes_manager.signal_dimension == 2:
f = plt.figure(figsize=(4 * per_row, 3 * rows))
else:
f = plt.figure()
for i in range(n):
if self.axes_manager.navigation_dimension == 1:
if same_window:
ax = plt.gca()
else:
if i > 0:
f = plt.figure()
plt.title('%s' % comp_label)
ax = f.add_subplot(111)
elif self.axes_manager.navigation_dimension == 2:
if same_window:
ax = f.add_subplot(rows, per_row, i + 1)
else:
if i > 0:
f = plt.figure()
plt.title('%s' % comp_label)
ax = f.add_subplot(111)
sigdraw._plot_loading(
loadings, idx=comp_ids[i], axes_manager=self.axes_manager,
no_nans=no_nans, calibrate=calibrate, cmap=cmap,
comp_label=comp_label, ax=ax, same_window=same_window,
axes_decor=axes_decor)
if not same_window:
fig_list.append(f)
if same_window: # Main title for same window
title = '%s' % comp_label
if self.axes_manager.navigation_dimension == 1:
plt.title(title)
else:
plt.suptitle(title)
try:
plt.tight_layout()
except BaseException:
pass
if not same_window:
if with_factors:
return fig_list, self._plot_factors_or_pchars(
factors, comp_ids=comp_ids, calibrate=calibrate,
same_window=same_window, comp_label=comp_label,
per_row=per_row)
else:
return fig_list
else:
if self.axes_manager.navigation_dimension == 1:
plt.legend(ncol=loadings.shape[0] // 2, loc='best')
animate_legend(f)
if with_factors:
return f, self._plot_factors_or_pchars(factors,
comp_ids=comp_ids,
calibrate=calibrate,
same_window=same_window,
comp_label=comp_label,
per_row=per_row)
else:
return f
def _export_factors(self,
factors,
folder=None,
comp_ids=None,
multiple_files=True,
save_figures=False,
save_figures_format='png',
factor_prefix=None,
factor_format=None,
comp_label=None,
cmap=plt.cm.gray,
plot_shifts=True,
plot_char=4,
img_data=None,
same_window=False,
calibrate=True,
quiver_color='white',
vector_scale=1,
no_nans=True, per_row=3):
from hyperspy._signals.signal2d import Signal2D
from hyperspy._signals.signal1d import Signal1D
if multiple_files is None:
multiple_files = True
if factor_format is None:
factor_format = 'hspy'
# Select the desired factors
if comp_ids is None:
comp_ids = range(factors.shape[1])
elif not hasattr(comp_ids, '__iter__'):
comp_ids = range(comp_ids)
mask = np.zeros(factors.shape[1], dtype=np.bool)
for idx in comp_ids:
mask[idx] = 1
factors = factors[:, mask]
if save_figures is True:
plt.ioff()
fac_plots = self._plot_factors_or_pchars(factors,
comp_ids=comp_ids,
same_window=same_window,
comp_label=comp_label,
img_data=img_data,
plot_shifts=plot_shifts,
plot_char=plot_char,
cmap=cmap,
per_row=per_row,
quiver_color=quiver_color,
vector_scale=vector_scale)
for idx in range(len(comp_ids)):
filename = '%s_%02i.%s' % (factor_prefix, comp_ids[idx],
save_figures_format)
if folder is not None:
filename = Path(folder, filename)
ensure_directory(filename)
_args = {'dpi': 600,
'format': save_figures_format}
fac_plots[idx].savefig(filename, **_args)
plt.ion()
elif multiple_files is False:
if self.axes_manager.signal_dimension == 2:
# factor images
axes_dicts = []
axes = self.axes_manager.signal_axes[::-1]
shape = (axes[1].size, axes[0].size)
factor_data = np.rollaxis(
factors.reshape((shape[0], shape[1], -1)), 2)
axes_dicts.append(axes[0].get_axis_dictionary())
axes_dicts.append(axes[1].get_axis_dictionary())
axes_dicts.append({'name': 'factor_index',
'scale': 1.,
'offset': 0.,
'size': int(factors.shape[1]),
'units': 'factor',
'index_in_array': 0, })
s = Signal2D(factor_data,
axes=axes_dicts,
metadata={
'General': {'title': '%s from %s' % (
factor_prefix,
self.metadata.General.title),
}})
elif self.axes_manager.signal_dimension == 1:
axes = [self.axes_manager.signal_axes[0].get_axis_dictionary(),
{'name': 'factor_index',
'scale': 1.,
'offset': 0.,
'size': int(factors.shape[1]),
'units': 'factor',
'index_in_array': 0,
}]
axes[0]['index_in_array'] = 1
s = Signal1D(
factors.T, axes=axes, metadata={
"General": {
'title': '%s from %s' %
(factor_prefix, self.metadata.General.title), }})
filename = '%ss.%s' % (factor_prefix, factor_format)
if folder is not None:
filename = Path(folder, filename)
s.save(filename)
else: # Separate files
if self.axes_manager.signal_dimension == 1:
axis_dict = self.axes_manager.signal_axes[0].\
get_axis_dictionary()
axis_dict['index_in_array'] = 0
for dim, index in zip(comp_ids, range(len(comp_ids))):
s = Signal1D(factors[:, index],
axes=[axis_dict, ],
metadata={
"General": {'title': '%s from %s' % (
factor_prefix,
self.metadata.General.title),
}})
filename = '%s-%i.%s' % (factor_prefix,
dim,
factor_format)
if folder is not None:
filename = Path(folder, filename)
s.save(filename)
if self.axes_manager.signal_dimension == 2:
axes = self.axes_manager.signal_axes
axes_dicts = [axes[0].get_axis_dictionary(),
axes[1].get_axis_dictionary()]
axes_dicts[0]['index_in_array'] = 0
axes_dicts[1]['index_in_array'] = 1
factor_data = factors.reshape(
self.axes_manager._signal_shape_in_array + [-1, ])
for dim, index in zip(comp_ids, range(len(comp_ids))):
im = Signal2D(factor_data[..., index],
axes=axes_dicts,
metadata={
"General": {'title': '%s from %s' % (
factor_prefix,
self.metadata.General.title),
}})
filename = '%s-%i.%s' % (factor_prefix,
dim,
factor_format)
if folder is not None:
filename = Path(folder, filename)
im.save(filename)
def _export_loadings(self,
loadings,
folder=None,
comp_ids=None,
multiple_files=True,
loading_prefix=None,
loading_format="hspy",
save_figures_format='png',
comp_label=None,
cmap=plt.cm.gray,
save_figures=False,
same_window=False,
calibrate=True,
no_nans=True,
per_row=3):
from hyperspy._signals.signal2d import Signal2D
from hyperspy._signals.signal1d import Signal1D
if multiple_files is None:
multiple_files = True
if loading_format is None:
loading_format = 'hspy'
if comp_ids is None:
comp_ids = range(loadings.shape[0])
elif not hasattr(comp_ids, '__iter__'):
comp_ids = range(comp_ids)
mask = np.zeros(loadings.shape[0], dtype=np.bool)
for idx in comp_ids:
mask[idx] = 1
loadings = loadings[mask]
if save_figures is True:
plt.ioff()
sc_plots = self._plot_loadings(loadings, comp_ids=comp_ids,
calibrate=calibrate,
same_window=same_window,
comp_label=comp_label,
cmap=cmap, no_nans=no_nans,
per_row=per_row)
for idx in range(len(comp_ids)):
filename = '%s_%02i.%s' % (loading_prefix, comp_ids[idx],
save_figures_format)
if folder is not None:
filename = Path(folder, filename)
ensure_directory(filename)
_args = {'dpi': 600,
'format': save_figures_format}
sc_plots[idx].savefig(filename, **_args)
plt.ion()
elif multiple_files is False:
if self.axes_manager.navigation_dimension == 2:
axes_dicts = []
axes = self.axes_manager.navigation_axes[::-1]
shape = (axes[1].size, axes[0].size)
loading_data = loadings.reshape((-1, shape[0], shape[1]))
axes_dicts.append(axes[0].get_axis_dictionary())
axes_dicts[0]['index_in_array'] = 1
axes_dicts.append(axes[1].get_axis_dictionary())
axes_dicts[1]['index_in_array'] = 2
axes_dicts.append({'name': 'loading_index',
'scale': 1.,
'offset': 0.,
'size': int(loadings.shape[0]),
'units': 'factor',
'index_in_array': 0, })
s = Signal2D(loading_data,
axes=axes_dicts,
metadata={
"General": {'title': '%s from %s' % (
loading_prefix,
self.metadata.General.title),
}})
elif self.axes_manager.navigation_dimension == 1:
cal_axis = self.axes_manager.navigation_axes[0].\
get_axis_dictionary()
cal_axis['index_in_array'] = 1
axes = [{'name': 'loading_index',
'scale': 1.,
'offset': 0.,
'size': int(loadings.shape[0]),
'units': 'comp_id',
'index_in_array': 0, },
cal_axis]
s = Signal2D(loadings,
axes=axes,
metadata={
"General": {'title': '%s from %s' % (
loading_prefix,
self.metadata.General.title),
}})
filename = '%ss.%s' % (loading_prefix, loading_format)
if folder is not None:
filename = Path(folder, filename)
s.save(filename)
else: # Separate files
if self.axes_manager.navigation_dimension == 1:
axis_dict = self.axes_manager.navigation_axes[0].\
get_axis_dictionary()
axis_dict['index_in_array'] = 0
for dim, index in zip(comp_ids, range(len(comp_ids))):
s = Signal1D(loadings[index],
axes=[axis_dict, ])
filename = '%s-%i.%s' % (loading_prefix,
dim,
loading_format)
if folder is not None:
filename = Path(folder, filename)
s.save(filename)
elif self.axes_manager.navigation_dimension == 2:
axes_dicts = []
axes = self.axes_manager.navigation_axes[::-1]
shape = (axes[0].size, axes[1].size)
loading_data = loadings.reshape((-1, shape[0], shape[1]))
axes_dicts.append(axes[0].get_axis_dictionary())
axes_dicts[0]['index_in_array'] = 0
axes_dicts.append(axes[1].get_axis_dictionary())
axes_dicts[1]['index_in_array'] = 1
for dim, index in zip(comp_ids, range(len(comp_ids))):
s = Signal2D(loading_data[index, ...],
axes=axes_dicts,
metadata={
"General": {'title': '%s from %s' % (
loading_prefix,
self.metadata.General.title),
}})
filename = '%s-%i.%s' % (loading_prefix,
dim,
loading_format)
if folder is not None:
filename = Path(folder, filename)
s.save(filename)
def plot_decomposition_factors(self,
comp_ids=None,
calibrate=True,
same_window=True,
title=None,
cmap=plt.cm.gray,
per_row=3,
**kwargs,
):
"""Plot factors from a decomposition. In case of 1D signal axis, each
factors line can be toggled on and off by clicking on their
corresponding line in the legend.
Parameters
----------
comp_ids : None, int, or list (of ints)
If `comp_ids` is ``None``, maps of all components will be
returned if the `output_dimension` was defined when executing
:py:meth:`~hyperspy.learn.mva.MVA.decomposition`. Otherwise it
raises a :py:exc:`ValueError`.
If `comp_ids` is an int, maps of components with ids from 0 to
the given value will be returned. If `comp_ids` is a list of
ints, maps of components with ids contained in the list will be
returned.
calibrate : bool
If ``True``, calibrates plots where calibration is available
from the axes_manager. If ``False``, plots are in pixels/channels.
same_window : bool
If ``True``, plots each factor to the same window. They are
not scaled. Default is ``True``.
title : str
Title of the matplotlib plot or label of the line in the legend
when the dimension of factors is 1 and ``same_window`` is ``True``.
cmap : :py:class:`~matplotlib.colors.Colormap`
The colormap used for the factor images, or for peak
characteristics. Default is the matplotlib gray colormap
(``plt.cm.gray``).
per_row : int
The number of plots in each row, when the `same_window`
parameter is ``True``.
See also
--------
plot_decomposition_loadings, plot_decomposition_results
"""
if self.axes_manager.signal_dimension > 2:
raise NotImplementedError("This method cannot plot factors of "
"signals of dimension higher than 2."
"You can use "
"`plot_decomposition_results` instead.")
if self.learning_results.factors is None:
raise RuntimeError("No learning results found. A 'decomposition' "
"needs to be performed first.")
if same_window is None:
same_window = True
if self.learning_results.factors is None:
raise RuntimeError("Run a decomposition first.")
factors = self.learning_results.factors
if comp_ids is None:
if self.learning_results.output_dimension:
comp_ids = self.learning_results.output_dimension
else:
raise ValueError(
"Please provide the number of components to plot via the "
"`comp_ids` argument.")
if title is None:
title = self._get_plot_title('Decomposition factors of',
same_window=same_window)
return self._plot_factors_or_pchars(factors,
comp_ids=comp_ids,
calibrate=calibrate,
same_window=same_window,
comp_label=title,
cmap=cmap,
per_row=per_row)
def plot_bss_factors(
self,
comp_ids=None,
calibrate=True,
same_window=True,
title=None,
cmap=plt.cm.gray,
per_row=3,
**kwargs,
):
"""Plot factors from blind source separation results. In case of 1D
signal axis, each factors line can be toggled on and off by clicking
on their corresponding line in the legend.
Parameters
----------
comp_ids : None, int, or list (of ints)
If `comp_ids` is ``None``, maps of all components will be
returned. If it is an int, maps of components with ids from 0 to
the given value will be returned. If `comp_ids` is a list of
ints, maps of components with ids contained in the list will be
returned.
calibrate : bool
If ``True``, calibrates plots where calibration is available
from the axes_manager. If ``False``, plots are in pixels/channels.
same_window : bool
if ``True``, plots each factor to the same window. They are
not scaled. Default is ``True``.
title : str
Title of the matplotlib plot or label of the line in the legend
when the dimension of factors is 1 and ``same_window`` is ``True``.
cmap : :py:class:`~matplotlib.colors.Colormap`
The colormap used for the factor images, or for peak
characteristics. Default is the matplotlib gray colormap
(``plt.cm.gray``).
per_row : int
The number of plots in each row, when the `same_window`
parameter is ``True``.
See also
--------
plot_bss_loadings, plot_bss_results
"""
if self.axes_manager.signal_dimension > 2:
raise NotImplementedError("This method cannot plot factors of "
"signals of dimension higher than 2."
"You can use "
"`plot_decomposition_results` instead.")
if self.learning_results.bss_factors is None:
raise RuntimeError("No learning results found. A "
"'blind_source_separation' needs to be "
"performed first.")
if same_window is None:
same_window = True
factors = self.learning_results.bss_factors
if title is None:
title = self._get_plot_title('BSS factors of',
same_window=same_window)
return self._plot_factors_or_pchars(factors,
comp_ids=comp_ids,
calibrate=calibrate,
same_window=same_window,
comp_label=title,
per_row=per_row)
def plot_decomposition_loadings(self,
comp_ids=None,
calibrate=True,
same_window=True,
title=None,
with_factors=False,
cmap=plt.cm.gray,
no_nans=False,
per_row=3,
axes_decor='all',
**kwargs,