-
Notifications
You must be signed in to change notification settings - Fork 281
/
Copy pathmodel.py
2297 lines (1904 loc) · 82.5 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
"""Implementation of the Model interface."""
from copy import deepcopy
from functools import wraps
import inspect
import json
import operator
import warnings
from asteval import valid_symbol_name
import numpy as np
from scipy.special import erf
from scipy.stats import t
import lmfit
from . import Minimizer, Parameter, Parameters, lineshapes
from .confidence import conf_interval
from .jsonutils import HAS_DILL, decode4js, encode4js
from .minimizer import MinimizerResult
from .printfuncs import ci_report, fit_report, fitreport_html_table
tiny = 1.e-15
# Use pandas.isnull for aligning missing data if pandas is available.
# otherwise use numpy.isnan
try:
from pandas import Series, isnull
except ImportError:
isnull = np.isnan
Series = type(NotImplemented)
def _align(var, mask, data):
"""Align missing data, if pandas is available."""
if isinstance(data, Series) and isinstance(var, Series):
return var.reindex_like(data).dropna()
elif mask is not None:
return var[mask]
return var
try:
import matplotlib # noqa: F401
_HAS_MATPLOTLIB = True
except Exception:
_HAS_MATPLOTLIB = False
def _ensureMatplotlib(function):
if _HAS_MATPLOTLIB:
@wraps(function)
def wrapper(*args, **kws):
return function(*args, **kws)
return wrapper
def no_op(*args, **kwargs):
print('matplotlib module is required for plotting the results')
return no_op
def get_reducer(option):
"""Factory function to build a parser for complex numbers.
Parameters
----------
option : {'real', 'imag', 'abs', 'angle'}
Implements the NumPy function with the same name.
Returns
-------
callable
See docstring for `reducer` below.
"""
if option not in ['real', 'imag', 'abs', 'angle']:
raise ValueError(f"Invalid option ('{option}') for function 'propagate_err'.")
def reducer(array):
"""Convert a complex array to a real array.
Several conversion methods are available and it does nothing to a
purely real array.
Parameters
----------
array : array-like
Input array. If complex, will be converted to real array via
one of the following NumPy functions: :numpydoc:`real`,
:numpydoc:`imag`, :numpydoc:`abs`, or :numpydoc:`angle`.
Returns
-------
numpy.array
Returned array will be purely real.
"""
if any(np.iscomplex(array)):
parsed_array = getattr(np, option)(array)
else:
parsed_array = array
return parsed_array
return reducer
def propagate_err(z, dz, option):
"""Perform error propagation on a vector of complex uncertainties.
Required to get values for magnitude (abs) and phase (angle)
uncertainty.
Parameters
----------
z : array-like
Array of complex or real numbers.
dz : array-like
Array of uncertainties corresponding to `z`. Must satisfy
``numpy.shape(dz) == numpy.shape(z)``.
option : {'real', 'imag', 'abs', 'angle'}
How to convert the array `z` to an array with real numbers.
Returns
-------
numpy.array
Returned array will be purely real.
Notes
-----
Uncertainties are ``1/weights``. If the weights provided are real,
they are assumed to apply equally to the real and imaginary parts. If
the weights are complex, the real part of the weights are applied to
the real part of the residual and the imaginary part is treated
correspondingly.
In the case where ``option='angle'`` and ``numpy.abs(z) == 0`` for any
value of `z` the phase angle uncertainty becomes the entire circle and
so a value of `math:pi` is returned.
In the case where ``option='abs'`` and ``numpy.abs(z) == 0`` for any
value of `z` the magnitude uncertainty is approximated by
``numpy.abs(dz)`` for that value.
"""
if option not in ['real', 'imag', 'abs', 'angle']:
raise ValueError(f"Invalid option ('{option}') for function 'propagate_err'.")
if z.shape != dz.shape:
raise ValueError(f"shape of z: {z.shape} != shape of dz: {dz.shape}")
# Check the main vector for complex. Do nothing if real.
if any(np.iscomplex(z)):
# if uncertainties are real, apply them equally to
# real and imaginary parts
if all(np.isreal(dz)):
dz = dz+1j*dz
if option == 'real':
err = np.real(dz)
elif option == 'imag':
err = np.imag(dz)
elif option in ['abs', 'angle']:
rz = np.real(z)
iz = np.imag(z)
rdz = np.real(dz)
idz = np.imag(dz)
# Don't spit out warnings for divide by zero. Will fix these later.
with np.errstate(divide='ignore', invalid='ignore'):
if option == 'abs':
# Standard error propagation for abs = sqrt(re**2 + im**2)
err = np.true_divide(np.sqrt((iz*idz)**2+(rz*rdz)**2),
np.abs(z))
# For abs = 0, error is +/- abs(rdz + j idz)
err[err == np.inf] = np.abs(dz)[err == np.inf]
if option == 'angle':
# Standard error propagation for angle = arctan(im/re)
err = np.true_divide(np.sqrt((rz*idz)**2+(iz*rdz)**2),
np.abs(z)**2)
# For abs = 0, error is +/- pi (i.e. the whole circle)
err[err == np.inf] = np.pi
else:
err = dz
return err
class Model:
"""Create a model from a user-supplied model function."""
_forbidden_args = ('data', 'weights', 'params')
_invalid_ivar = "Invalid independent variable name ('%s') for function %s"
_invalid_par = "Invalid parameter name ('%s') for function %s"
_invalid_hint = "unknown parameter hint '%s' for param '%s'"
_hint_names = ('value', 'vary', 'min', 'max', 'expr')
valid_forms = ()
def __init__(self, func, independent_vars=None, param_names=None,
nan_policy='raise', prefix='', name=None, **kws):
"""
The model function will normally take an independent variable
(generally, the first argument) and a series of arguments that are
meant to be parameters for the model. It will return an array of
data to model some data as for a curve-fitting problem.
Parameters
----------
func : callable
Function to be wrapped.
independent_vars : :obj:`list` of :obj:`str`, optional
Arguments to `func` that are independent variables (default is
None).
param_names : :obj:`list` of :obj:`str`, optional
Names of arguments to `func` that are to be made into
parameters (default is None).
nan_policy : {'raise', 'propagate', 'omit'}, optional
How to handle NaN and missing values in data. See Notes below.
prefix : str, optional
Prefix used for the model.
name : str, optional
Name for the model. When None (default) the name is the same
as the model function (`func`).
**kws : dict, optional
Additional keyword arguments to pass to model function.
Notes
-----
1. Parameter names are inferred from the function arguments, and a
residual function is automatically constructed.
2. The model function must return an array that will be the same
size as the data being modeled.
3. `nan_policy` sets what to do when a NaN or missing value is
seen in the data. Should be one of:
- `'raise'` : raise a `ValueError` (default)
- `'propagate'` : do nothing
- `'omit'` : drop missing data
Examples
--------
The model function will normally take an independent variable
(generally, the first argument) and a series of arguments that are
meant to be parameters for the model. Thus, a simple peak using a
Gaussian defined as:
>>> import numpy as np
>>> def gaussian(x, amp, cen, wid):
... return amp * np.exp(-(x-cen)**2 / wid)
can be turned into a Model with:
>>> gmodel = Model(gaussian)
this will automatically discover the names of the independent
variables and parameters:
>>> print(gmodel.param_names, gmodel.independent_vars)
['amp', 'cen', 'wid'], ['x']
"""
self.func = func
if not isinstance(prefix, str):
prefix = ''
if len(prefix) > 0 and not valid_symbol_name(prefix):
raise ValueError(f"'{prefix}' is not a valid Model prefix")
self._prefix = prefix
self._param_root_names = param_names # will not include prefixes
self.independent_vars = independent_vars
self._func_allargs = []
self._func_haskeywords = False
self.nan_policy = nan_policy
self.opts = kws
# the following has been changed from OrderedSet for the time being
self.param_hints = {}
self._param_names = []
self._parse_params()
if self.independent_vars is None:
self.independent_vars = []
if name is None and hasattr(self.func, '__name__'):
name = self.func.__name__
self._name = name
def _reprstring(self, long=False):
out = self._name
opts = []
if len(self._prefix) > 0:
opts.append(f"prefix='{self._prefix}'")
if long:
for k, v in self.opts.items():
opts.append(f"{k}='{v}'")
if len(opts) > 0:
out = f"{out}, {', '.join(opts)}"
return f"Model({out})"
def _get_state(self):
"""Save a Model for serialization.
Note: like the standard-ish '__getstate__' method but not really
useful with Pickle.
"""
funcdef = None
if HAS_DILL:
funcdef = self.func
if self.func.__name__ == '_eval':
funcdef = self.expr
state = (self.func.__name__, funcdef, self._name, self._prefix,
self.independent_vars, self._param_root_names,
self.param_hints, self.nan_policy, self.opts)
return (state, None, None)
def _set_state(self, state, funcdefs=None):
"""Restore Model from serialization.
Note: like the standard-ish '__setstate__' method but not really
useful with Pickle.
Parameters
----------
state
Serialized state from `_get_state`.
funcdefs : dict, optional
Dictionary of function definitions to use to construct Model.
"""
return _buildmodel(state, funcdefs=funcdefs)
def dumps(self, **kws):
"""Dump serialization of Model as a JSON string.
Parameters
----------
**kws : optional
Keyword arguments that are passed to `json.dumps`.
Returns
-------
str
JSON string representation of Model.
See Also
--------
loads, json.dumps
"""
return json.dumps(encode4js(self._get_state()), **kws)
def dump(self, fp, **kws):
"""Dump serialization of Model to a file.
Parameters
----------
fp : file-like object
An open and `.write()`-supporting file-like object.
**kws : optional
Keyword arguments that are passed to `json.dumps`.
Returns
-------
int
Return value from `fp.write()`: the number of characters
written.
See Also
--------
dumps, load, json.dump
"""
return fp.write(self.dumps(**kws))
def loads(self, s, funcdefs=None, **kws):
"""Load Model from a JSON string.
Parameters
----------
s : str
Input JSON string containing serialized Model.
funcdefs : dict, optional
Dictionary of function definitions to use to construct Model.
**kws : optional
Keyword arguments that are passed to `json.loads`.
Returns
-------
Model
Model created from JSON string.
See Also
--------
dump, dumps, load, json.loads
"""
tmp = decode4js(json.loads(s, **kws))
return self._set_state(tmp, funcdefs=funcdefs)
def load(self, fp, funcdefs=None, **kws):
"""Load JSON representation of Model from a file-like object.
Parameters
----------
fp : file-like object
An open and `.read()`-supporting file-like object.
funcdefs : dict, optional
Dictionary of function definitions to use to construct Model.
**kws : optional
Keyword arguments that are passed to `loads`.
Returns
-------
Model
Model created from `fp`.
See Also
--------
dump, loads, json.load
"""
return self.loads(fp.read(), funcdefs=funcdefs, **kws)
@property
def name(self):
"""Return Model name."""
return self._reprstring(long=False)
@name.setter
def name(self, value):
self._name = value
@property
def prefix(self):
"""Return Model prefix."""
return self._prefix
@prefix.setter
def prefix(self, value):
"""Change Model prefix."""
self._prefix = value
self._set_paramhints_prefix()
self._param_names = []
self._parse_params()
def _set_paramhints_prefix(self):
"""Reset parameter hints for prefix: intended to be overwritten."""
@property
def param_names(self):
"""Return the parameter names of the Model."""
return self._param_names
def __repr__(self):
"""Return representation of Model."""
return f"<lmfit.Model: {self.name}>"
def copy(self, **kwargs):
"""DOES NOT WORK."""
raise NotImplementedError("Model.copy does not work. Make a new Model")
def _parse_params(self):
"""Build parameters from function arguments."""
if self.func is None:
return
kw_args = {}
keywords_ = None
# need to fetch the following from the function signature:
# pos_args: list of positional argument names
# kw_args: dict of keyword arguments with default values
# keywords_: name of **kws argument or None
# 1. limited support for asteval functions as the model functions:
if hasattr(self.func, 'argnames') and hasattr(self.func, 'kwargs'):
pos_args = self.func.argnames[:]
for name, defval in self.func.kwargs:
kw_args[name] = defval
# 2. modern, best-practice approach: use inspect.signature
else:
pos_args = []
sig = inspect.signature(self.func)
for fnam, fpar in sig.parameters.items():
if fpar.kind == fpar.VAR_KEYWORD:
keywords_ = fnam
elif fpar.kind == fpar.POSITIONAL_OR_KEYWORD:
if fpar.default == fpar.empty:
pos_args.append(fnam)
else:
kw_args[fnam] = fpar.default
elif fpar.kind == fpar.VAR_POSITIONAL:
raise ValueError(f"varargs '*{fnam}' is not supported")
# inspection done
self._func_haskeywords = keywords_ is not None
self._func_allargs = pos_args + list(kw_args.keys())
allargs = self._func_allargs
if len(allargs) == 0 and keywords_ is not None:
return
# default independent_var = 1st argument
if self.independent_vars is None:
self.independent_vars = [pos_args[0]]
# default param names: all positional args
# except independent variables
self.def_vals = {}
might_be_param = []
if self._param_root_names is None:
self._param_root_names = pos_args[:]
for key, val in kw_args.items():
if (not isinstance(val, bool) and
isinstance(val, (float, int))):
self._param_root_names.append(key)
self.def_vals[key] = val
elif val is None:
might_be_param.append(key)
for p in self.independent_vars:
if p in self._param_root_names:
self._param_root_names.remove(p)
new_opts = {}
for opt, val in self.opts.items():
if (opt in self._param_root_names or opt in might_be_param and
isinstance(val, Parameter)):
self.set_param_hint(opt, value=val.value,
min=val.min, max=val.max, expr=val.expr)
elif opt in self._func_allargs:
new_opts[opt] = val
self.opts = new_opts
if self._prefix is None:
self._prefix = ''
names = [f"{self._prefix}{pname}" for pname in self._param_root_names]
# check variables names for validity
# The implicit magic in fit() requires us to disallow some
fname = self.func.__name__
for arg in self.independent_vars:
if arg not in allargs or arg in self._forbidden_args:
raise ValueError(self._invalid_ivar % (arg, fname))
for arg in names:
if (self._strip_prefix(arg) not in allargs or
arg in self._forbidden_args):
raise ValueError(self._invalid_par % (arg, fname))
# the following as been changed from OrderedSet for the time being.
self._param_names = names[:]
def set_param_hint(self, name, **kwargs):
"""Set *hints* to use when creating parameters with `make_params()`.
The given hint can include optional bounds and constraints
``(value, vary, min, max, expr)``, which will be used by
`Model.make_params()` when building default parameters.
While this can be used to set initial values, `Model.make_params` or
the function `create_params` should be preferred for creating
parameters with initial values.
The intended use here is to control how a Model should create
parameters, such as setting bounds that are required by the mathematics
of the model (for example, that a peak width cannot be negative), or to
define common constrained parameters.
Parameters
----------
name : str
Parameter name, can include the models `prefix` or not.
**kwargs : optional
Arbitrary keyword arguments, needs to be a Parameter attribute.
Can be any of the following:
- value : float, optional
Numerical Parameter value.
- vary : bool, optional
Whether the Parameter is varied during a fit (default is
True).
- min : float, optional
Lower bound for value (default is ``-numpy.inf``, no lower
bound).
- max : float, optional
Upper bound for value (default is ``numpy.inf``, no upper
bound).
- expr : str, optional
Mathematical expression used to constrain the value during
the fit.
Example
--------
>>> model = GaussianModel()
>>> model.set_param_hint('sigma', min=0)
"""
npref = len(self._prefix)
if npref > 0 and name.startswith(self._prefix):
name = name[npref:]
if name not in self.param_hints:
self.param_hints[name] = {}
for key, val in kwargs.items():
if key in self._hint_names:
self.param_hints[name][key] = val
else:
warnings.warn(self._invalid_hint % (key, name))
def print_param_hints(self, colwidth=8):
"""Print a nicely aligned text-table of parameter hints.
Parameters
----------
colwidth : int, optional
Width of each column, except for first and last columns.
"""
name_len = max(len(s) for s in self.param_hints)
print('{:{name_len}} {:>{n}} {:>{n}} {:>{n}} {:>{n}} {:{n}}'
.format('Name', 'Value', 'Min', 'Max', 'Vary', 'Expr',
name_len=name_len, n=colwidth))
line = ('{name:<{name_len}} {value:{n}g} {min:{n}g} {max:{n}g} '
'{vary!s:>{n}} {expr}')
for name, values in sorted(self.param_hints.items()):
pvalues = dict(name=name, value=np.nan, min=-np.inf, max=np.inf,
vary=True, expr='')
pvalues.update(**values)
print(line.format(name_len=name_len, n=colwidth, **pvalues))
def make_params(self, verbose=False, **kwargs):
"""Create a Parameters object for a Model.
Parameters
----------
verbose : bool, optional
Whether to print out messages (default is False).
**kwargs : optional
Parameter names and initial values or dictionaries of
values and attributes.
Returns
---------
params : Parameters
Parameters object for the Model.
Notes
-----
1. Parameter values can be numbers (floats or ints) to set the parameter
value, or dictionaries with any of the following keywords:
``value``, ``vary``, ``min``, ``max``, ``expr``, ``brute_step``,
``is_init_value`` to set those parameter attributes.
2. This method will also apply any default values or parameter hints
that may have been defined for the model.
Example
--------
>>> gmodel = GaussianModel(prefix='peak_') + LinearModel(prefix='bkg_')
>>> gmodel.make_params(peak_center=3200, bkg_offset=0, bkg_slope=0,
... peak_amplitdue=dict(value=100, min=2),
... peak_sigma=dict(value=25, min=0, max=1000))
"""
params = Parameters()
def setpar(par, val):
# val is expected to be float-like or a dict: must have 'value' or 'expr' key
if isinstance(val, dict):
dval = val
else:
dval = {'value': float(val)}
if len(dval) < 1 or not ('value' in dval or 'expr' in dval):
raise TypeError(f'Invalid parameter value for {par}: {val}')
par.set(**dval)
# make sure that all named parameters are in params
for name in self.param_names:
if name in params:
par = params[name]
else:
par = Parameter(name=name)
par._delay_asteval = True
basename = name[len(self._prefix):]
# apply defaults from model function definition
if basename in self.def_vals:
par.value = self.def_vals[basename]
if par.value in (None, -np.inf, np.inf, np.nan):
for key, val in self.def_vals.items():
if key in name.lower():
par.value = val
# apply defaults from parameter hints
if basename in self.param_hints:
hint = self.param_hints[basename]
for item in self._hint_names:
if item in hint:
setattr(par, item, hint[item])
# apply values passed in through kw args
if basename in kwargs:
setpar(par, kwargs[basename])
if name in kwargs:
setpar(par, kwargs[basename])
params.add(par)
if verbose:
print(f' - Adding parameter "{name}"')
# next build parameters defined in param_hints
# note that composites may define their own additional
# convenience parameters here
for basename, hint in self.param_hints.items():
name = f"{self._prefix}{basename}"
if name in params:
par = params[name]
else:
par = Parameter(name=name)
params.add(par)
if verbose:
print(f' - Adding parameter for hint "{name}"')
par._delay_asteval = True
for item in self._hint_names:
if item in hint:
setattr(par, item, hint[item])
if basename in kwargs:
setpar(par, kwargs[basename])
# Add the new parameter to self._param_names
if name not in self._param_names:
self._param_names.append(name)
for p in params.values():
p._delay_asteval = False
return params
def guess(self, data, x, **kws):
"""Guess starting values for the parameters of a Model.
This is not implemented for all models, but is available for many
of the built-in models.
Parameters
----------
data : array_like
Array of data (i.e., y-values) to use to guess parameter values.
x : array_like
Array of values for the independent variable (i.e., x-values).
**kws : optional
Additional keyword arguments, passed to model function.
Returns
-------
Parameters
Initial, guessed values for the parameters of a Model.
Raises
------
NotImplementedError
If the `guess` method is not implemented for a Model.
Notes
-----
Should be implemented for each model subclass to run
`self.make_params()`, update starting values and return a
Parameters object.
.. versionchanged:: 1.0.3
Argument ``x`` is now explicitly required to estimate starting values.
"""
cname = self.__class__.__name__
msg = f'guess() not implemented for {cname}'
raise NotImplementedError(msg)
def _residual(self, params, data, weights, **kwargs):
"""Return the residual.
Default residual: ``(data-model)*weights``.
If the model returns complex values, the residual is computed by
treating the real and imaginary parts separately. In this case, if
the weights provided are real, they are assumed to apply equally
to the real and imaginary parts. If the weights are complex, the
real part of the weights are applied to the real part of the
residual and the imaginary part is treated correspondingly.
Since the underlying `scipy.optimize` routines expect
``numpy.float`` arrays, the only complex type supported is
``complex``.
The "ravels" throughout are necessary to support `pandas.Series`.
"""
model = self.eval(params, **kwargs)
if self.nan_policy == 'raise' and not np.all(np.isfinite(model)):
msg = ('The model function generated NaN values and the fit '
'aborted! Please check your model function and/or set '
'boundaries on parameters where applicable. In cases like '
'this, using "nan_policy=\'omit\'" will probably not work.')
raise ValueError(msg)
diff = model - data
if diff.dtype == complex:
# data/model are complex
diff = diff.ravel().view(float)
if weights is not None:
if weights.dtype == complex:
# weights are complex
weights = weights.ravel().view(float)
else:
# real weights but complex data
weights = (weights + 1j * weights).ravel().view(float)
if weights is not None:
diff *= weights
return np.asarray(diff).ravel() # for compatibility with pandas.Series
def _strip_prefix(self, name):
npref = len(self._prefix)
if npref > 0 and name.startswith(self._prefix):
name = name[npref:]
return name
def make_funcargs(self, params=None, kwargs=None, strip=True):
"""Convert parameter values and keywords to function arguments."""
if params is None:
params = {}
if kwargs is None:
kwargs = {}
out = {}
out.update(self.opts)
# 0: if a keyword argument is going to overwrite a parameter,
# save that value so it can be restored before returning
saved_values = {}
for name, val in kwargs.items():
if name in params:
saved_values[name] = params[name].value
params[name].value = val
if len(saved_values) > 0:
params.update_constraints()
# 1. fill in in all parameter values
for name, par in params.items():
if strip:
name = self._strip_prefix(name)
if name in self._func_allargs or self._func_haskeywords:
out[name] = par.value
# 2. for each function argument, use 'prefix+varname' in params,
# avoiding possible name collisions with unprefixed params
if len(self._prefix) > 0:
for fullname in self._param_names:
if fullname in params:
name = self._strip_prefix(fullname)
if name in self._func_allargs or self._func_haskeywords:
out[name] = params[fullname].value
# 3. kwargs might directly update function arguments
for name, val in kwargs.items():
if strip:
name = self._strip_prefix(name)
if name in self._func_allargs or self._func_haskeywords:
out[name] = val
# 4. finally, reset any values that have overwritten parameter values
for name, val in saved_values.items():
params[name].value = val
return out
def _make_all_args(self, params=None, **kwargs):
"""Generate **all** function args for all functions."""
args = {}
for key, val in self.make_funcargs(params, kwargs).items():
args[f"{self._prefix}{key}"] = val
return args
def eval(self, params=None, **kwargs):
"""Evaluate the model with supplied parameters and keyword arguments.
Parameters
-----------
params : Parameters, optional
Parameters to use in Model.
**kwargs : optional
Additional keyword arguments to pass to model function.
Returns
-------
numpy.ndarray, float, int or complex
Value of model given the parameters and other arguments.
Notes
-----
1. if `params` is None, the values for all parameters are expected
to be provided as keyword arguments.
2. If `params` is given, and a keyword argument for a parameter value
is also given, the keyword argument will be used in place of the value
in the value in `params`.
3. all non-parameter arguments for the model function, **including
all the independent variables** will need to be passed in using
keyword arguments.
4. The return types are generally `numpy.ndarray`, but may depends on
the model function and input independent variables. That is, return
values may be Python `float`, `int`, or `complex` values.
"""
return self.func(**self.make_funcargs(params, kwargs))
@property
def components(self):
"""Return components for composite model."""
return [self]
def eval_components(self, params=None, **kwargs):
"""Evaluate the model with the supplied parameters.
Parameters
-----------
params : Parameters, optional
Parameters to use in Model.
**kwargs : optional
Additional keyword arguments to pass to model function.
Returns
-------
dict
Keys are prefixes for component model, values are value of
each component.
"""
key = self._prefix
if len(key) < 1:
key = self._name
return {key: self.eval(params=params, **kwargs)}
def fit(self, data, params=None, weights=None, method='leastsq',
iter_cb=None, scale_covar=True, verbose=False, fit_kws=None,
nan_policy=None, calc_covar=True, max_nfev=None, **kwargs):
"""Fit the model to the data using the supplied Parameters.
Parameters
----------
data : array_like
Array of data to be fit.
params : Parameters, optional
Parameters to use in fit (default is None).
weights : array_like, optional
Weights to use for the calculation of the fit residual [i.e.,
`weights*(data-fit)`]. Default is None; must have the same size as
`data`.
method : str, optional
Name of fitting method to use (default is `'leastsq'`).
iter_cb : callable, optional
Callback function to call at each iteration (default is None).
scale_covar : bool, optional
Whether to automatically scale the covariance matrix when
calculating uncertainties (default is True).
verbose : bool, optional
Whether to print a message when a new parameter is added
because of a hint (default is True).
fit_kws : dict, optional
Options to pass to the minimizer being used.
nan_policy : {'raise', 'propagate', 'omit'}, optional
What to do when encountering NaNs when fitting Model.
calc_covar : bool, optional
Whether to calculate the covariance matrix (default is True)
for solvers other than `'leastsq'` and `'least_squares'`.
Requires the ``numdifftools`` package to be installed.
max_nfev : int or None, optional
Maximum number of function evaluations (default is None). The
default value depends on the fitting method.
**kwargs : optional
Arguments to pass to the model function, possibly overriding
parameters.
Returns
-------
ModelResult
Notes
-----
1. if `params` is None, the values for all parameters are expected
to be provided as keyword arguments. Mixing `params` and
keyword arguments is deprecated (see `Model.eval`).
2. all non-parameter arguments for the model function, **including
all the independent variables** will need to be passed in using
keyword arguments.
3. Parameters are copied on input, so that the original Parameter objects
are unchanged, and the updated values are in the returned `ModelResult`.
Examples
--------
Take ``t`` to be the independent variable and data to be the curve
we will fit. Use keyword arguments to set initial guesses: