forked from hyperspy/hyperspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
2553 lines (2199 loc) · 98.4 KB
/
model.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>.
import copy
import importlib
import logging
import os
import tempfile
import warnings
from contextlib import contextmanager
from functools import partial
import cloudpickle
import numpy as np
import dask.array as da
from dask.diagnostics import ProgressBar
import scipy.odr as odr
from scipy.linalg import svd
from scipy.optimize import (
differential_evolution,
leastsq,
least_squares,
minimize,
OptimizeResult
)
from hyperspy.component import Component
from hyperspy.components1d import Expression
from hyperspy.defaults_parser import preferences
from hyperspy.docstrings.model import FIT_PARAMETERS_ARG
from hyperspy.docstrings.signal import SHOW_PROGRESSBAR_ARG
from hyperspy.events import Event, Events, EventSuppressor
from hyperspy.extensions import ALL_EXTENSIONS
from hyperspy.external.mpfit.mpfit import mpfit
from hyperspy.external.progressbar import progressbar
from hyperspy.misc.export_dictionary import (
export_to_dictionary,
load_from_dictionary,
parse_flag_string,
reconstruct_object
)
from hyperspy.misc.model_tools import CurrentModelValues, _calculate_covariance
from hyperspy.misc.slicing import copy_slice_from_whitelist
from hyperspy.misc.utils import (
display,
dummy_context_manager,
shorten_name,
slugify,
stash_active_state,
)
from hyperspy.signal import BaseSignal
from hyperspy.ui_registry import add_gui_method
from hyperspy.misc.machine_learning import import_sklearn
_logger = logging.getLogger(__name__)
_COMPONENTS = ALL_EXTENSIONS["components1D"]
_COMPONENTS.update(ALL_EXTENSIONS["components1D"])
EXSPY_HSPY_COMPONENTS = ("EELSArctan", "EELSCLEdge", "DoublePowerLaw", "Vignetting", "PESCoreLineShape", "SEE", "PESVoigt", "VolumePlasmonDrude")
def _twinned_parameter(parameter):
"""
Used in linear fitting. Since twinned parameters are not free, we need to
construct a mapping between the twinned parameter and the parameter
component to which the (non-free) twinned parameter component value needs
to be added.
Returns
-------
parameter when there is a twin and this twin is free
None when there is no twin or when the twin is not non-free itself, which
implies that the original parameter is not free
"""
twin = parameter.twin
if twin is None:
# there is no twin
return None
elif twin.free:
# this is the parameter we are looking for
return twin
elif twin.twin:
# recursive to find the final not twinned parameter
return _twinned_parameter(twin)
else:
# the twinned parameter is not twinned and it is not free, which means
# that the original parameter is twinned to a non-free parameter and
# therefore not free itself!
return None
def reconstruct_component(comp_dictionary, **init_args):
# Restoring of Voigt and Arctan components saved with Hyperspy <v1.6
if (comp_dictionary['_id_name'] == "Voigt" and
len(comp_dictionary['parameters']) > 4):
# in HyperSpy 1.6 the old Voigt component was moved to PESVoigt
if comp_dictionary['parameters'][4]['_id_name'] == "resolution":
comp_dictionary['_id_name'] = "PESVoigt"
_logger.info("Legacy Voigt component converted to PESVoigt during file reading.")
if (comp_dictionary['_id_name'] == "Arctan" and 'minimum_at_zero' in comp_dictionary):
# in HyperSpy 1.6 the old Arctan component was moved to EELSArctan
if comp_dictionary['minimum_at_zero'] == True:
comp_dictionary['_id_name'] = "EELSArctan"
_logger.info("Legacy Arctan component converted to EELSArctan during file reading.")
_id = comp_dictionary['_id_name']
if _id in _COMPONENTS:
_class = getattr(
importlib.import_module(
_COMPONENTS[_id]["module"]), _COMPONENTS[_id]["class"])
elif "_class_dump" in comp_dictionary:
# When a component is not registered using the extension mechanism,
# it is serialized using cloudpickle.
try:
_class = cloudpickle.loads(comp_dictionary['_class_dump'])
except TypeError: # pragma: no cover
# https://github.com/cloudpipe/cloudpickle/blob/master/README.md
raise TypeError("Pickling is not (always) supported between python "
"versions. As a result the custom class cannot be "
"loaded. Consider adding a custom Component using the "
"extension mechanism.")
else:
# For component saved with hyperspy <2.0 and moved to exspy
if comp_dictionary["_id_name"] in EXSPY_HSPY_COMPONENTS:
comp_dictionary["package"] = "exspy"
raise ImportError(
f'Loading the {comp_dictionary["_id_name"]} component ' +
'failed because the component is provided by the ' +
f'`{comp_dictionary["package"]}` Python package, but ' +
f'{comp_dictionary["package"]} is not installed.')
return _class(**init_args)
class ModelComponents(object):
"""Container for model components.
Useful to provide tab completion when running in IPython.
"""
def __init__(self, model):
self._model = model
def __repr__(self):
signature = "%4s | %19s | %19s | %19s"
ans = signature % ('#',
'Attribute Name',
'Component Name',
'Component Type')
ans += "\n"
ans += signature % ('-' * 4, '-' * 19, '-' * 19, '-' * 19)
if self._model:
for i, c in enumerate(self._model):
ans += "\n"
name_string = c.name
variable_name = slugify(name_string, valid_variable_name=True)
component_type = c.__class__.__name__
variable_name = shorten_name(variable_name, 19)
name_string = shorten_name(name_string, 19)
component_type = shorten_name(component_type, 19)
ans += signature % (i,
variable_name,
name_string,
component_type)
return ans
@add_gui_method(toolkey="hyperspy.Model")
class BaseModel(list):
"""Model and data fitting tools applicable to signals of both one and two
dimensions.
Models of one-dimensional signals should use the
:py:class:`~hyperspy.models.model1d` and models of two-dimensional signals
should use the :class:`~hyperspy.models.model2d`.
A model is constructed as a linear combination of
:py:mod:`~hyperspy._components` that are added to the model using the
:py:meth:`~hyperspy.model.BaseModel.append` or
:py:meth:`~hyperspy.model.BaseModel.extend`. There are many predefined
components available in the in the :py:mod:`~hyperspy._components`
module. If needed, new components can be created easily using the code of
existing components as a template.
Once defined, the model can be fitted to the data using :meth:`fit` or
:py:meth:`~hyperspy.model.BaseModel.multifit`. Once the optimizer reaches
the convergence criteria or the maximum number of iterations the new value
of the component parameters are stored in the components.
It is possible to access the components in the model by their name or by
the index in the model. An example is given at the end of this docstring.
Attributes
----------
signal : BaseSignal instance
It contains the data to fit.
chisq : :py:class:`~.signal.BaseSignal` of float
Chi-squared of the signal (or np.nan if not yet fit)
dof : :py:class:`~.signal.BaseSignal` of int
Degrees of freedom of the signal (0 if not yet fit)
components : :py:class:`~.model.ModelComponents` instance
The components of the model are attributes of this class. This provides
a convenient way to access the model components when working in IPython
as it enables tab completion.
Methods
-------
set_signal_range, remove_signal range, reset_signal_range,
add signal_range.
Customize the signal range to fit.
fit, multifit
Fit the model to the data at the current position or the
full dataset.
save_parameters2file, load_parameters_from_file
Save/load the parameter values to/from a file.
plot
Plot the model and the data.
enable_plot_components, disable_plot_components
Plot each component separately. (Use after `plot`.)
set_current_values_to
Set the current value of all the parameters of the given component as
the value for all the dataset.
enable_adjust_position, disable_adjust_position
Enable/disable interactive adjustment of the position of the components
that have a well defined position. (Use after `plot`).
fit_component
Fit just the given component in the given signal range, that can be
set interactively.
set_parameters_not_free, set_parameters_free
Fit the `free` status of several components and parameters at once.
See also
--------
:py:class:`~hyperspy.models.model1d.Model1D`
:py:class:`~hyperspy.models.model2d.Model2D`
"""
def __init__(self):
self.events = Events()
self.events.fitted = Event("""
Event that triggers after fitting changed at least one parameter.
The event triggers after the fitting step was finished, and only of
at least one of the parameters changed.
Arguments
---------
obj : Model
The Model that the event belongs to
""", arguments=['obj'])
# The private _binned attribute is created to store temporarily
# axes.is_binned or not. This avoids evaluating it during call of
# the model function, which is detrimental to the performances of
# multifit(). Setting it to None ensures that the existing behaviour
# is preserved.
self._binned = None
def __hash__(self):
# This is needed to simulate a hashable object so that PySide does not
# raise an exception when using windows.connect
return id(self)
def _get_current_data(self, onlyactive=False, component_list=None, binned=None):
"""Evaluate the model numerically. Implementation requested in all sub-classes"""
raise NotImplementedError
@property
def convolved(self):
raise NotImplementedError("This model does not support convolution.")
@convolved.setter
def convolved(self, value):
# This is for compatibility with model saved with HyperSpy < 2.0
if value:
raise NotImplementedError("This model does not support convolution.")
else:
_logger.warning(
"The `convolved` attribute is deprecated. It is only available in models that implement convolution.")
def set_signal_range_from_mask(self, mask):
"""
Use the signal ranges as defined by the mask
Parameters
----------
mask : numpy.ndarray of bool
A boolean array defining the signal range. Must be the same
shape as the ``signal_shape``. Where array values are ``True``,
signal will be fitted, otherwise not.
See Also
--------
set_signal_range, add_signal_range,
remove_signal_range, reset_signal_range
"""
if mask.dtype != bool:
raise ValueError(
"`mask` argument must be an array with boolean dtype."
)
if mask.shape != self.axes_manager.signal_shape:
raise ValueError(
"`mask` argument must have the same shape as `signal_shape`."
)
self._channel_switches[:] = mask
def store(self, name=None):
"""Stores current model in the original signal
Parameters
----------
name : {None, str}
Stored model name. Auto-generated if left empty
"""
if self.signal is None:
raise ValueError("Cannot store models with no signal")
s = self.signal
s.models.store(self, name)
def save(self, file_name, name=None, **kwargs):
"""Saves signal and its model to a file
Parameters
----------
file_name : str
Name of the file
name : {None, str}
Stored model name. Auto-generated if left empty
**kwargs :
Other keyword arguments are passed onto `BaseSignal.save()`
"""
if self.signal is None:
raise ValueError("Currently cannot save models with no signal")
else:
self.store(name)
self.signal.save(file_name, **kwargs)
def _load_dictionary(self, dic):
"""Load data from dictionary.
Parameters
----------
dic : dict
A dictionary containing at least the following fields:
* _whitelist: a dictionary with keys used as references of save
attributes, for more information, see
:py:func:`~.misc.export_dictionary.load_from_dictionary`
* components: a dictionary, with information about components of
the model (see
:py:meth:`~.component.Parameter.as_dictionary`
documentation for more details)
* any field from _whitelist.keys()
"""
if 'components' in dic:
while len(self) != 0:
self.remove(self[0])
id_dict = {}
for comp in dic['components']:
init_args = {}
for k, flags_str in comp['_whitelist'].items():
if not len(flags_str):
continue
if 'init' in parse_flag_string(flags_str):
init_args[k] = reconstruct_object(flags_str, comp[k])
self.append(reconstruct_component(comp, **init_args))
id_dict.update(self[-1]._load_dictionary(comp))
# deal with twins:
for comp in dic['components']:
for par in comp['parameters']:
for tw in par['_twins']:
id_dict[tw].twin = id_dict[par['self']]
if '_whitelist' in dic:
channel_switches = dic["_whitelist"].pop("channel_switches", None)
if channel_switches:
# Before channel_switches was privatised
dic["_whitelist"]["_channel_switches"] = channel_switches
load_from_dictionary(self, dic)
def __repr__(self):
title = self.signal.metadata.General.title
class_name = str(self.__class__).split("'")[1].split('.')[-1]
if len(title):
return "<%s, title: %s>" % (
class_name, self.signal.metadata.General.title)
else:
return "<%s>" % class_name
def _get_component(self, thing):
if isinstance(thing, int) or isinstance(thing, str):
thing = self[thing]
elif np.iterable(thing):
thing = [self._get_component(athing) for athing in thing]
return thing
elif not isinstance(thing, Component):
raise ValueError("Not a component or component id.")
if thing in self:
return thing
else:
raise ValueError("The component is not in the model.")
def insert(self, **kwargs):
raise NotImplementedError
def append(self, thing):
"""Add component to Model.
Parameters
----------
thing: `Component` instance.
"""
if not isinstance(thing, Component):
raise ValueError(
"Only `Component` instances can be added to a model")
# Check if any of the other components in the model has the same name
if thing in self:
raise ValueError("Component already in model")
component_name_list = [component.name for component in self]
if thing.name:
name_string = thing.name
else:
name_string = thing.__class__.__name__
if name_string in component_name_list:
temp_name_string = name_string
index = 0
while temp_name_string in component_name_list:
temp_name_string = name_string + "_" + str(index)
index += 1
name_string = temp_name_string
thing.name = name_string
thing._axes_manager = self.axes_manager
thing._create_arrays()
list.append(self, thing)
thing.model = self
setattr(self.components, slugify(name_string,
valid_variable_name=True), thing)
if self._plot_active:
self._connect_parameters2update_plot(components=[thing])
self.signal._plot.signal_plot.update()
def extend(self, iterable):
"""Append multiple components to the model.
Parameters
----------
iterable: iterable of `Component` instances.
"""
for object in iterable:
self.append(object)
def __delitem__(self, thing):
thing = self.__getitem__(thing)
self.remove(thing)
def remove(self, thing):
"""Remove component from model.
Examples
--------
>>> s = hs.signals.Signal1D(np.empty(1))
>>> m = s.create_model()
>>> g = hs.model.components1D.Gaussian()
>>> m.append(g)
You could remove `g` like this
>>> m.remove(g)
Like this:
>>> m.remove("Gaussian")
Or like this:
>>> m.remove(0)
"""
thing = self._get_component(thing)
if not np.iterable(thing):
thing = [thing, ]
for athing in thing:
for parameter in athing.parameters:
# Remove the parameter from its twin _twins
parameter.twin = None
for twin in [twin for twin in parameter._twins]:
twin.twin = None
list.remove(self, athing)
athing.model = None
if self._plot_active:
self.signal._plot.signal_plot.update()
def as_signal(self, component_list=None, out_of_range_to_nan=True,
show_progressbar=None, out=None, **kwargs):
"""Returns a recreation of the dataset using the model.
By default, the signal range outside of the fitted range is filled with nans.
Parameters
----------
component_list : list of HyperSpy components, optional
If a list of components is given, only the components given in the
list is used in making the returned spectrum. The components can
be specified by name, index or themselves.
out_of_range_to_nan : bool
If True the signal range outside of the fitted range is filled with
nans. Default True.
%s
out : {None, BaseSignal}
The signal where to put the result into. Convenient for parallel
processing. If None (default), creates a new one. If passed, it is
assumed to be of correct shape and dtype and not checked.
Returns
-------
BaseSignal : An instance of the same class as `BaseSignal`.
Examples
--------
>>> s = hs.signals.Signal1D(np.random.random((10,100)))
>>> m = s.create_model()
>>> l1 = hs.model.components1D.Lorentzian()
>>> l2 = hs.model.components1D.Lorentzian()
>>> m.append(l1)
>>> m.append(l2)
>>> s1 = m.as_signal()
>>> s2 = m.as_signal(component_list=[l1])
"""
if show_progressbar is None:
show_progressbar = preferences.General.show_progressbar
if out is None:
data = np.empty(self.signal.data.shape, dtype='float')
data.fill(np.nan)
signal = self.signal.__class__(
data,
axes=self.signal.axes_manager._get_axes_dicts())
signal.set_signal_type(signal.metadata.Signal.signal_type)
signal.metadata.General.title = (
self.signal.metadata.General.title + " from fitted model")
else:
signal = out
data = signal.data
if not out_of_range_to_nan:
# we want the full signal range, including outside the fitted
# range, we need to set all the _channel_switches to True
channel_switches_backup = copy.copy(self._channel_switches)
self._channel_switches[:] = True
self._as_signal_iter(
component_list=component_list,
show_progressbar=show_progressbar,
data=data
)
if not out_of_range_to_nan:
# Restore the _channel_switches, previously set
self._channel_switches[:] = channel_switches_backup
return signal
as_signal.__doc__ %= SHOW_PROGRESSBAR_ARG
def _as_signal_iter(self, data, component_list=None,
show_progressbar=None):
#BUG: with lazy signal returns lazy signal with numpy array
# Note that show_progressbar can be an int to determine the progressbar
# position for a thread-friendly bars. Otherwise race conditions are
# ugly...
if show_progressbar is None: # pragma: no cover
show_progressbar = preferences.General.show_progressbar
with stash_active_state(self if component_list else []):
if component_list:
component_list = [self._get_component(x)
for x in component_list]
for component_ in self:
active = component_ in component_list
if component_.active_is_multidimensional:
if active:
continue # Keep active_map
component_.active_is_multidimensional = False
component_.active = active
maxval = self.axes_manager._get_iterpath_size()
enabled = show_progressbar and (maxval != 0)
pbar = progressbar(total=maxval, disable=not enabled,
position=show_progressbar, leave=True)
for index in self.axes_manager:
self.fetch_stored_values(only_fixed=False)
data[self.axes_manager._getitem_tuple][
np.where(self._channel_switches)] = self._get_current_data(
onlyactive=True).ravel()
pbar.update(1)
@property
def _plot_active(self):
if self._plot is not None and self._plot.is_active:
return True
else:
return False
def _connect_parameters2update_plot(self, components):
if self._plot_active is False:
return
for i, component in enumerate(components):
component.events.active_changed.connect(
self._model_line._auto_update_line, [])
for parameter in component.parameters:
parameter.events.value_changed.connect(
self._model_line._auto_update_line, [])
def _disconnect_parameters2update_plot(self, components):
if self._model_line is None:
return
for component in components:
component.events.active_changed.disconnect(
self._model_line._auto_update_line)
for parameter in component.parameters:
parameter.events.value_changed.disconnect(
self._model_line._auto_update_line)
def update_plot(self, render_figure=False, update_ylimits=False, **kwargs):
"""Update model plot.
The updating can be suspended using `suspend_update`.
See Also
--------
suspend_update
"""
if self._plot_active is True and self._suspend_update is False:
try:
if self._model_line is not None:
self._model_line.update(render_figure=render_figure,
update_ylimits=update_ylimits)
if self._plot_components:
for component in self.active_components:
self._update_component_line(component)
except BaseException:
self._disconnect_parameters2update_plot(components=self)
@contextmanager
def suspend_update(self, update_on_resume=True):
"""Prevents plot from updating until 'with' clause completes.
See Also
--------
update_plot
"""
es = EventSuppressor()
es.add(self.axes_manager.events.indices_changed)
if self._model_line:
f = self._model_line._auto_update_line
for c in self:
es.add(c.events, f)
if c._position:
es.add(c._position.events)
for p in c.parameters:
es.add(p.events, f)
for c in self:
if hasattr(c, '_component_line'):
f = c._component_line._auto_update_line
es.add(c.events, f)
for p in c.parameters:
es.add(p.events, f)
old = self._suspend_update
self._suspend_update = True
with es.suppress():
yield
self._suspend_update = old
if update_on_resume is True:
for c in self:
position = c._position
if position:
position.events.value_changed.trigger(
obj=position, value=position.value)
self.update_plot(render_figure=True, update_ylimits=False)
def _close_plot(self):
if self._plot_components is True:
self.disable_plot_components()
self._disconnect_parameters2update_plot(components=self)
self._model_line = None
def enable_plot_components(self):
if self._plot is None or self._plot_components:
return
for component in self.active_components:
self._plot_component(component)
self._plot_components = True
def disable_plot_components(self):
if self._plot is None:
return
if self._plot_components:
for component in self.active_components:
self._disable_plot_component(component)
self._plot_components = False
@property
def _free_parameters(self):
# TODO: improve the use of this property
"""Get the free parameters of active components."""
components = [c for c in self if c.active]
return tuple([p for c in components for p in c.parameters if p.free])
def _set_p0(self):
"""
Sets the initial values for the parameters used in the curve fitting
functions
"""
# Stores the values and is fed as initial values to the fitter
self.p0 = ()
for component in self.active_components:
for parameter in component.free_parameters:
self.p0 = (self.p0 + (parameter.value,)
if parameter._number_of_elements == 1
else self.p0 + parameter.value)
def _set_boundaries(self, bounded=True):
"""Generate the boundary list.
Necessary before fitting with a boundary aware optimizer.
Parameters
----------
bounded : bool, default True
If True, loops through the model components and
populates the free parameter boundaries.
Returns
-------
None
"""
if not bounded:
self.free_parameters_boundaries = None
else:
self.free_parameters_boundaries = []
for component in self.active_components:
for param in component.free_parameters:
if param._number_of_elements == 1:
self.free_parameters_boundaries.append((param._bounds))
else:
self.free_parameters_boundaries.extend((param._bounds))
def _bounds_as_tuple(self):
"""Converts parameter bounds to tuples for least_squares()"""
if self.free_parameters_boundaries is None:
return (-np.inf, np.inf)
return tuple(
(a if a is not None else -np.inf, b if b is not None else np.inf)
for a, b in self.free_parameters_boundaries
)
def _set_mpfit_parameters_info(self, bounded=True):
"""Generate the boundary list for mpfit.
Parameters
----------
bounded : bool, default True
If True, loops through the model components and
populates the free parameter boundaries.
Returns
-------
None
"""
if not bounded:
self.mpfit_parinfo = None
else:
self.mpfit_parinfo = []
for component in self.active_components:
for param in component.free_parameters:
limited = [False, False]
limits = [0, 0]
if param.bmin is not None:
limited[0] = True
limits[0] = param.bmin
if param.bmax is not None:
limited[1] = True
limits[1] = param.bmax
if param._number_of_elements == 1:
self.mpfit_parinfo.append(
{"limited": limited, "limits": limits}
)
else:
self.mpfit_parinfo.extend(
({"limited": limited, "limits": limits},)
* param._number_of_elements
)
def ensure_parameters_in_bounds(self):
"""For all active components, snaps their free parameter values to
be within their boundaries (if bounded). Does not touch the array of
values.
"""
for component in self:
if component.active:
for param in component.free_parameters:
bmin = -np.inf if param.bmin is None else param.bmin
bmax = np.inf if param.bmax is None else param.bmax
if param._number_of_elements == 1:
if not bmin <= param.value <= bmax:
min_d = np.abs(param.value - bmin)
max_d = np.abs(param.value - bmax)
if min_d < max_d:
param.value = bmin
else:
param.value = bmax
else:
values = np.array(param.value)
if param.bmin is not None:
minmask = values < bmin
values[minmask] = bmin
if param.bmax is not None:
maxmask = values > bmax
values[maxmask] = bmax
param.value = tuple(values)
def store_current_values(self):
""" Store the parameters of the current coordinates into the
`parameter.map` array and sets the `is_set` array attribute to True.
If the parameters array has not being defined yet it creates it filling
it with the current parameters at the current indices in the array."""
for component in self:
if component.active:
component.store_current_parameters_in_map()
def fetch_stored_values(self, only_fixed=False, update_on_resume=True):
"""Fetch the value of the parameters that have been previously stored
in `parameter.map['values']` if `parameter.map['is_set']` is `True` for
those indices.
If it is not previously stored, the current values from `parameter.value`
are used, which are typically from the fit in the previous pixel of a
multidimensional signal.
Parameters
----------
only_fixed : bool, optional
If True, only the fixed parameters are fetched.
update_on_resume : bool, optional
If True, update the model plot after values are updated.
See Also
--------
store_current_values
"""
cm = self.suspend_update if self._plot_active else dummy_context_manager
with cm(update_on_resume=update_on_resume):
for component in self:
component.fetch_stored_values(only_fixed=only_fixed)
def _on_navigating(self):
"""Same as fetch_stored_values but without update_on_resume since
the model plot is updated in the figure update callback.
"""
self.fetch_stored_values(only_fixed=False, update_on_resume=False)
def fetch_values_from_array(self, array, array_std=None):
"""Fetch the parameter values from the given array, optionally also
fetching the standard deviations.
Places the parameter values into both `m.p0` (the initial values
for the optimizer routine) and `component.parameter.value` and
`...std`, for parameters in active components ordered by their
position in the model and component.
Parameters
----------
array : array
array with the parameter values
array_std : {None, array}
array with the standard deviations of parameters
"""
self.p0 = array
self._fetch_values_from_p0(p_std=array_std)
def _fetch_values_from_p0(self, p_std=None):
"""Fetch the parameter values from the output of the optimizer `self.p0`,
placing them in their appropriate `component.parameter.value` and `...std`
Parameters
----------
p_std : array, optional
array containing the corresponding standard deviation.
"""
comp_p_std = None
counter = 0
for component in self: # Cut the parameters list
if component.active is True:
if p_std is not None:
comp_p_std = p_std[
counter: counter +
component._nfree_param]
component.fetch_values_from_array(
self.p0[counter: counter + component._nfree_param],
comp_p_std, onlyfree=True)
counter += component._nfree_param
def _model2plot(self, axes_manager, out_of_range2nans=True):
old_axes_manager = None
if axes_manager is not self.axes_manager:
old_axes_manager = self.axes_manager
self.axes_manager = axes_manager
self.fetch_stored_values()
s = self._get_current_data(onlyactive=True)
if old_axes_manager is not None:
self.axes_manager = old_axes_manager
self.fetch_stored_values()
if out_of_range2nans is True:
ns = np.empty(self.axis.axis.shape)
ns.fill(np.nan)
ns[np.where(self._channel_switches)] = s
s = ns
return s
def _model_function(self, param):
self.p0 = param
self._fetch_values_from_p0()
to_return = self._get_current_data(onlyactive=True, binned=self._binned)
return to_return
@property
def active_components(self):
"""List all nonlinear parameters."""
return tuple([c for c in self if c.active])
def _convolve_component_values(self, component_values):
raise NotImplementedError("This model does not support convolution")
def _compute_constant_term(self, component):
"""Gets the value of any (non-free) constant term"""
signal_shape = self.axes_manager.signal_shape[::-1]
data = component._constant_term * np.ones(signal_shape)
return data.T[np.where(self._channel_switches)[::-1]].T
def _linear_fit(self, optimizer="lstsq", calculate_errors=False,
only_current=True, weights=None, **kwargs):
"""
Multivariate linear fitting
Parameters
----------
optimizer : str, default is "lstsq"
'lstsq' - Default, supports lazy signal
'ridge_regression' - Supports regularisation, doesn't support lazy
signal.
calculate_errors : bool, default is False
If True, calculate the errors.
only_current : bool, default is True
Fit the current index only, instead of the whole navigation space.
kwargs : dict, optional
Keywords arguments are passed to
:py:func:`sklearn.linear_model.ridge_regression`.