-
Notifications
You must be signed in to change notification settings - Fork 306
/
fit_functions.py
1068 lines (828 loc) · 31.2 KB
/
fit_functions.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
"""
``FitFunction`` classes designed to assist in curve fitting of swept Langmuir
traces.
"""
__all__ = [
"AbstractFitFunction",
"Exponential",
"ExponentialPlusLinear",
"ExponentialPlusOffset",
"Linear",
]
import numbers
import numpy as np
from abc import ABC, abstractmethod
from collections import namedtuple
from scipy.optimize import curve_fit, fsolve
from scipy.stats import linregress
from typing import Optional, Tuple
from warnings import warn
from plasmapy.utils.decorators import modify_docstring
#: Named tuple for :meth:`AbstractFitFunction.root_solve`.
_RootResults = namedtuple("RootResults", ("root", "err"))
class AbstractFitFunction(ABC):
"""
Abstract class for defining fit functions :math:`f(x)` and the tools for
fitting the function to a set of data.
"""
_param_names = NotImplemented # type: Tuple[str, ...]
def __init__(
self,
params: Tuple[float, ...] = None,
param_errors: Tuple[float, ...] = None,
):
"""
Parameters
----------
params: Tuple[float, ...], optional
Tuple of values for the function parameters. Equal in size to
:attr:`param_names`.
param_errors: Tuple[float, ...], optional
Tuple of values for the errors associated with the function
parameters. Equal in size to :attr:`param_names`.
"""
self._FitParamTuple = namedtuple("FitParamTuple", self._param_names)
if params is None:
self._params = None
else:
self.params = params
if param_errors is None:
self._param_errors = None
else:
self.param_errors = param_errors
self._curve_fit_results = None
self._rsq = None
def __call__(self, x, x_err=None, reterr=False):
"""
Direct call of the fit function :math:`f(x)`.
Parameters
----------
x: |array_like|
Dependent variables.
x_err: |array_like|, optional
Errors associated with the independent variables ``x``. Must be of
size one or equal to the size of ``x``.
reterr: bool, optional
(Default: `False`) If `True`, return an array of uncertainties
associated with the calculated independent variables
Returns
-------
y: `numpy.ndarray`
Corresponding dependent variables :math:`y=f(x)` of the independent
variables ``x``.
y_err: `numpy.ndarray`
Uncertainties associated with the calculated dependent variables
:math:`\\delta y`
"""
if reterr:
y_err, y = self.func_err(x, x_err=x_err, rety=True)
return y, y_err
y = self.func(x, *self.params)
return y
def __repr__(self):
return f"{self.__str__()} {self.__class__}"
@abstractmethod
def __str__(self):
...
@abstractmethod
def func(self, x, *args):
"""
The fit function. This signature of the function must first take the
independent variable followed by the parameters to be fitted as
separate arguments.
Parameters
----------
x: |array_like|
Independent variables to be passed to the fit function.
*args: Tuple[Union[float, int],...]
The parameters that will be adjusted to make the fit.
Returns
-------
`numpy.ndarray`:
The calculated dependent variables of the independent variables ``x``.
Notes
-----
* When sub-classing the definition should look something like::
def func(self, x, a, b, c):
x = self._check_x(x)
self._check_params(a, b, c)
return a * x ** 2 + b * x + c
"""
...
@abstractmethod
@modify_docstring(
prepend="""
Calculate dependent variable uncertainties :math:`\\delta y` for
dependent variables :math:`y=f(x)`.
""",
append="""
* When sub-classing the definition should look something like::
@modify_docstring(append=AbstractFitFunction.func_err.__original_doc__)
def func_err(self, x, x_err=None, rety=False):
'''
A simple docstring giving the equation for error propagation, but
excluding the parameter descriptions. The @modify_docstring
decorator will append the docstring from the parent class.
'''
x, x_err = self._check_func_err_params(x, x_err)
a, b, c = self.params
a_err, b_err, c_err = self.param_errors
# calculate error
if rety:
y = self.func(x, a, b, c)
return err, y
return err
""",
)
def func_err(self, x, x_err=None, rety=False):
"""
Parameters
----------
x: |array_like|
Independent variables to be passed to the fit function.
x_err: |array_like|, optional
Errors associated with the independent variables ``x``. Must be of
size one or equal to the size of ``x``.
rety: bool
Set `True` to also return the associated dependent variables
:math:`y = f(x)`.
Returns
-------
err: `numpy.ndarray`
The calculated uncertainties :math:`\\delta y` of the dependent
variables (:math:`y = f(x)`) of the independent variables ``x``.
y: `numpy.ndarray`, optional
(if ``rety == True``) The associated dependent variables
:math:`y = f(x)`.
Notes
-----
* A good reference for formulating propagation of uncertainty expressions is:
J. R. Taylor. *An Introduction to Error Analysis: The Study of
Uncertainties in Physical Measurements.* University Science Books,
second edition, August 1996 (ISBN: 093570275X)
"""
...
@property
def curve_fit_results(self):
"""
The results returned by the curve fitting routine used by
:attr:`curve_fit`. This is typically from `scipy.stats.linregress` or
`scipy.optimize.curve_fit`.
"""
return self._curve_fit_results
@property
def FitParamTuple(self):
"""
A `~collections.namedtuple` used for attributes :attr:`params` and
:attr:`param_errors`. The attribute :attr:`param_names` defines
the tuple field names.
"""
return self._FitParamTuple
@property
def params(self) -> Optional[tuple]:
"""The fitted parameters for the fit function."""
if self._params is None:
return self._params
else:
return self.FitParamTuple(*self._params)
@params.setter
def params(self, val) -> None:
if isinstance(val, self.FitParamTuple) or (
isinstance(val, (tuple, list))
and len(val) == len(self.param_names)
and all(isinstance(vv, numbers.Real) for vv in val)
):
self._params = tuple(val)
else:
raise ValueError(
f"Got {val} for 'val', expecting tuple of ints and "
f"floats of length {len(self.param_names)}."
)
@property
def param_errors(self) -> Optional[tuple]:
"""The associated errors of the fitted :attr:`params`."""
if self._param_errors is None:
return self._param_errors
else:
return self.FitParamTuple(*self._param_errors)
@param_errors.setter
def param_errors(self, val) -> None:
if isinstance(val, self.FitParamTuple) or (
isinstance(val, (tuple, list))
and len(val) == len(self.param_names)
and all(isinstance(vv, numbers.Real) for vv in val)
):
self._param_errors = tuple(val)
else:
raise ValueError(
f"Got {val} for 'val', expecting tuple of ints and "
f"floats of length {len(self.param_names)}."
)
@property
def param_names(self) -> Tuple[str, ...]:
"""Names of the fitted parameters."""
return self._param_names
@property
@abstractmethod
def latex_str(self) -> str:
"""LaTeX friendly representation of the fit function."""
...
def _check_func_err_params(self, x, x_err):
"""Check the ``x`` and ``x_err`` parameters for :meth:`func_err`."""
x = self._check_x(x)
if x_err is not None:
x_err = self._check_x(x_err)
if x_err.shape == ():
pass
elif x_err.shape != x.shape:
raise ValueError(
f"x_err shape {x_err.shape} must be equal the shape of "
f"x {x.shape}."
)
return x, x_err
@staticmethod
def _check_params(*args) -> None:
"""
Check fitting parameters so that they are an expected type for the
class functionality.
"""
for arg in args:
if not isinstance(arg, numbers.Real):
raise TypeError(
f"Expected int or float for parameter argument, got "
f"{type(arg)}."
)
@staticmethod
def _check_x(x):
"""
Check the independent variable ``x`` so that it is an expected
type for the class functionality.
"""
if isinstance(x, numbers.Real):
x = np.array(x)
else:
if not isinstance(x, np.ndarray):
x = np.array(x)
if not (
np.issubdtype(x.dtype, np.integer)
or np.issubdtype(x.dtype, np.floating)
):
raise TypeError(
"Argument x needs to be an array_like object of integers "
"or floats."
)
x = x.squeeze()
if x.shape == ():
# force x to be a scalar
x = x[()]
return x
def root_solve(self, x0):
"""
Solve for the root of the fit function (i.e. :math:`f(x_r) = 0`). This
method used `scipy.optimize.fsolve` to find the function roots.
Parameters
----------
x0: `~numpy.ndarray`
The starting estimate for the roots of :math:`f(x_r) = 0`.
Returns
-------
x : `~numpy.ndarray`
The solution (or the result of the last iteration for an
unsuccessful call).
x_err: `~numpy.ndarray`
The uncertainty associated with the root calculation. **Currently
this returns an array of** `numpy.nan` **values equal in shape to**
``x`` **, since there is no determined way to calculate the
uncertainties.**
Notes
-----
If the full output of `scipy.optimize.fsolve` is desired then one can do:
>>> func = Linear()
>>> func.params = (1.0, 5.0)
>>> func.param_errors = (0.0, 0.0)
>>> roots = fsolve(func, -4.0, full_output=True)
>>> roots
(array([-5.]),
{'nfev': 4,
'fjac': array([[-1.]]),
'r': array([-1.]),
'qtf': array([2.18...e-12]),
'fvec': 0.0},
1,
'The solution converged.')
"""
results = fsolve(self.func, x0, args=self.params)
root = np.squeeze(results[0])
err = np.tile(np.nan, root.shape)
if root.shape == ():
# force x to be a scalar
root = root[()]
err = np.nan
return _RootResults(root, err)
@property
def rsq(self):
"""
Coefficient of determination (r-squared) value of the fit.
.. math::
r^2 &= 1 - \\frac{SS_{res}}{SS_{tot}}
SS_{res} &= \\sum\\limits_{i} (y_i - f(x_i))^2
SS_{tot} &= \\sum\\limits_{i} (y_i - \\bar{y})^2
where :math:`(x_i, y_i)` are the sample data pairs, :math:`f(x_i)` is
the fitted dependent variable corresponding to :math:`x_i`, and
:math:`\\bar{y}` is the average of the :math:`y_i` values.
The :math:`r^2` value is an indicator of how close the points
:math:`(x_i, y_i)` lie to the model :math:`f(x)`. :math:`r^2` values
range between 0 and 1. Values close to 0 indicate that the points
are uncorrelated and have little tendency to lie close to the model,
whereas, values close to 1 indicate a high correlation to the model.
"""
return self._rsq
def curve_fit(self, xdata, ydata, **kwargs) -> None:
"""
Use a non-linear least squares method to fit the fit function to
(``xdata``, ``ydata``), using `scipy.optimize.curve_fit`. This will set
the attributes :attr:`params`, :attr:`param_errors`, and
:attr:`rsq`.
The results of `scipy.optimize.curve_fit` can be obtained via
:attr:`curve_fit_results`.
Parameters
----------
xdata: |array_like|
The independent variable where data is measured. Should be 1D of
length M.
ydata: |array_like|
The dependent data associated with ``xdata``.
**kwargs
Any keywords accepted by `scipy.optimize.curve_fit`.
Raises
------
ValueError
if either ``ydata`` or ``xdata`` contain `numpy.nan`'s, or if
incompatible options are used.
RuntimeError
if the least-squares minimization fails.
~scipy.optimize.OptimizeWarning
if covariance of the parameters can not be estimated.
"""
popt, pcov = curve_fit(self.func, xdata, ydata, **kwargs)
self._curve_fit_results = (popt, pcov)
self.params = tuple(popt.tolist())
self.param_errors = tuple(np.sqrt(np.diag(pcov)).tolist())
# calc rsq
# rsq = 1 - (ss_res / ss_tot)
residuals = ydata - self.func(xdata, *self.params)
ss_res = np.sum(residuals**2)
ss_tot = np.sum((ydata - np.mean(ydata)) ** 2)
self._rsq = 1 - (ss_res / ss_tot)
class Linear(AbstractFitFunction):
"""
A sub-class of `AbstractFitFunction` to represent a linear function.
.. math::
y &= f(x) = m \\, x + b
(\\delta y)^2 &= (x \\, \\delta m)^2 + (m \\, \\delta x)^2 + (\\delta b)^2
where :math:`m` and :math:`b` are real constants to be fitted and :math:`x` is
the independent variable. :math:`\\delta m`, :math:`\\delta b`, and
:math:`\\delta x` are the respective uncertainties for :math:`m`, :math:`b`,
and :math:`x`.
"""
_param_names = ("m", "b")
def __str__(self):
return "f(x) = m x + b"
@property
def latex_str(self) -> str:
return r"m x + b"
def func(self, x, m, b):
"""
The fit function, a linear function.
.. math::
f(x) = m \\, x + b
where :math:`m` and :math:`b` are real constants representing the
slope and intercept, respectively, and :math:`x` is the independent
variable.
Parameters
----------
x: |array_like|
Independent variable.
m: float
value for slope :math:`m`
b: float
value for intercept :math:`b`
Returns
-------
y: |array_like|
dependent variables corresponding to :math:`x`
"""
x = self._check_x(x)
self._check_params(m, b)
return m * x + b
@modify_docstring(append=AbstractFitFunction.func_err.__original_doc__)
def func_err(self, x, x_err=None, rety=False):
"""
Calculate dependent variable uncertainties :math:`\\delta y` for
dependent variables :math:`y=f(x)`.
.. math::
(\\delta y)^2 = (x \\, \\delta m)^2 + (m \\, \\delta x)^2 + (\\delta b)^2
"""
x, x_err = self._check_func_err_params(x, x_err)
m, b = self.params
m_err, b_err = self.param_errors
m_term = (m_err * x) ** 2
b_term = b_err**2
err = m_term + b_term
if x_err is not None:
x_term = (m * x_err) ** 2
err += x_term
err = np.sqrt(err)
if rety:
y = self.func(x, m, b)
return err, y
return err
@property
def rsq(self):
"""
Coefficient of determination (r-squared) value of the fit. Calculated
by `scipy.stats.linregress` from the fit.
"""
return self._rsq
def root_solve(self, *args, **kwargs):
"""
The root :math:`f(x_r) = 0` for the fit function.
.. math::
x_r &= \\frac{-b}{m}
\\delta x_r &= |x_r| \\sqrt{
\\left( \\frac{\\delta m}{m} \\right)^2
+ \\left( \\frac{\\delta b}{b} \\right)^2
}
Parameters
----------
*args
Not needed. This is to ensure signature comparability with
`AbstractFitFunction`.
**kwargs
Not needed. This is to ensure signature comparability with
`AbstractFitFunction`.
Returns
-------
root: float
The root value for the given fit :attr:`params`.
err: float
The uncertainty in the calculated root for the given fit
:attr:`params` and :attr:`param_errors`.
"""
m, b = self.params
if m == 0.0:
warn(
"Slope of Linear fit function is zero so no finite root exists. ",
RuntimeWarning,
)
return _RootResults(np.nan, np.nan)
root = -b / m
m_err, b_err = self.param_errors
m_term = (root * m_err / m) ** 2
b_term = (b_err / m) ** 2
err = np.sqrt(m_term + b_term)
return _RootResults(root, err)
def curve_fit(self, xdata, ydata, **kwargs) -> None:
"""
Calculate a linear least-squares regression of (``xdata``, ``ydata``)
using `scipy.stats.linregress`. This will set the attributes
:attr:`params`, :attr:`param_errors`, and :attr:`rsq`.
The results of `scipy.stats.linregress` can be obtained via
:attr:`curve_fit_results`.
Parameters
----------
xdata: |array_like|
The independent variable where data is measured. Should be 1D of
length M.
ydata: |array_like|
The dependent data associated with ``xdata``.
**kwargs
Any keywords accepted by `scipy.stats.linregress`.
"""
results = linregress(xdata, ydata, **kwargs)
self._curve_fit_results = results
m = results[0]
b = results[1]
self.params = (m, b)
m_err = results[4]
b_err = np.sum(xdata**2) - ((np.sum(xdata) ** 2) / xdata.size)
b_err = m_err * np.sqrt(1.0 / b_err)
self.param_errors = (m_err, b_err)
self._rsq = results[2] ** 2
class Exponential(AbstractFitFunction):
"""
A sub-class of `AbstractFitFunction` to represent an exponential with an
offset.
.. math::
y &= f(x) = a \\, e^{\\alpha \\, x}
\\left( \\frac{\\delta y}{|y|} \\right)^2 &=
\\left( \\frac{\\delta a}{a} \\right)^2
+ (x \\, \\delta \\alpha)^2
+ (\\alpha \\, \\delta x)^2
where :math:`a` and :math:`\\alpha` are the real constants to be fitted and
:math:`x` is the independent variable. :math:`\\delta a`,
:math:`\\delta \\alpha`, and :math:`\\delta x` are the respective
uncertainties for :math:`a`, :math:`\\alpha`, and :math:`x`.
"""
_param_names = ("a", "alpha")
def __str__(self):
return "f(x) = a exp(alpha x)"
@property
def latex_str(self) -> str:
return r"a \, \exp(\alpha x)"
def func(self, x, a, alpha):
"""
The fit function, a exponential function.
.. math::
f(x) = a \\, e^{\\alpha \\, x}
where :math:`a` and :math:`\\alpha` are real constants and :math:`x`
is the independent variable.
Parameters
----------
x: |array_like|
Independent variable.
a: float
value for the exponential "normalization" constant, :math:`a`
alpha: float
value for the growth constant, :math:`\\alpha`
Returns
-------
y: |array_like|
dependent variables corresponding to ``x``
"""
x = self._check_x(x)
self._check_params(a, alpha)
return a * np.exp(alpha * x)
@modify_docstring(append=AbstractFitFunction.func_err.__original_doc__)
def func_err(self, x, x_err=None, rety=False):
"""
Calculate dependent variable uncertainties :math:`\\delta y` for
dependent variables :math:`y=f(x)`.
.. math::
\\left( \\frac{\\delta y}{|y|} \\right)^2 =
\\left( \\frac{\\delta a}{a} \\right)^2
+ (x \\, \\delta \\alpha)^2
+ (\\alpha \\, \\delta x)^2
"""
x, x_err = self._check_func_err_params(x, x_err)
a, alpha = self.params
a_err, alpha_err = self.param_errors
y = self.func(x, a, alpha)
a_term = (a_err / a) ** 2
alpha_term = (x * alpha_err) ** 2
err = a_term + alpha_term
if x_err is not None:
x_term = (alpha * x_err) ** 2
err += x_term
err = np.abs(y) * np.sqrt(err)
return (err, y) if rety else err
def root_solve(self, *args, **kwargs):
"""
The root :math:`f(x_r) = 0` for the fit function. **An exponential has no
real roots.**
Parameters
----------
*args
Not needed. This is to ensure signature compatibility with
`AbstractFitFunction`.
**kwargs
Not needed. This is to ensure signature compatibility with
`AbstractFitFunction`.
Returns
-------
root: float
The root value for the given fit :attr:`params`.
err: float
The uncertainty in the calculated root for the given fit
:attr:`params` and :attr:`param_errors`.
"""
return _RootResults(np.nan, np.nan)
class ExponentialPlusLinear(AbstractFitFunction):
"""
A sub-class of `AbstractFitFunction` to represent an exponential with an
linear offset.
.. math::
y =& f(x) = a \\, e^{\\alpha \\, x} + m \\, x + b\\\\
(\\delta y)^2 =&
\\left( a e^{\\alpha x}\\right)^2 \\left[
\\left( \\frac{\\delta a}{a} \\right)^2
+ (x \\, \\delta \\alpha)^2
+ (\\alpha \\, \\delta x)^2
\\right]\\\\
& + \\left(2 \\, a \\, \\alpha \\, m \\, e^{\\alpha x}\\right)
(\\delta x)^2\\\\
& + \\left[(x \\, \\delta m)^2 + (\\delta b)^2 +(m \\, \\delta x)^2\\right]
where :math:`a`, :math:`\\alpha`, :math:`m`, and :math:`b` are the real
constants to be fitted and :math:`x` is the independent variable.
:math:`\\delta a`, :math:`\\delta \\alpha`, :math:`\\delta m`, :math:`\\delta b`,
and :math:`\\delta x` are the respective uncertainties for :math:`a`,
:math:`\\alpha`, :math:`m`, and :math:`b`, and :math:`x`.
"""
_param_names = ("a", "alpha", "m", "b")
def __init__(
self,
params: Tuple[float, ...] = None,
param_errors: Tuple[float, ...] = None,
):
self._exponential = Exponential()
self._linear = Linear()
super().__init__(params=params, param_errors=param_errors)
def __str__(self):
exp_str = self._exponential.__str__().replace("f(x) = ", "")
lin_str = self._linear.__str__().replace("f(x) = ", "")
return f"f(x) = {exp_str} + {lin_str}"
@property
def latex_str(self) -> str:
exp_str = self._exponential.latex_str
lin_str = self._linear.latex_str
return rf"{exp_str} + {lin_str}"
@AbstractFitFunction.params.setter
def params(self, val) -> None:
AbstractFitFunction.params.fset(self, val)
self._exponential.params = (self.params.a, self.params.alpha)
self._linear.params = (self.params.m, self.params.b)
@AbstractFitFunction.param_errors.setter
def param_errors(self, val) -> None:
AbstractFitFunction.param_errors.fset(self, val)
self._exponential.param_errors = (
self.param_errors.a,
self.param_errors.alpha,
)
self._linear.param_errors = (self.param_errors.m, self.param_errors.b)
def func(self, x, a, alpha, m, b):
"""
The fit function, an exponential with a linear offset.
.. math::
f(x) = a \\, e^{\\alpha \\, x} + m \\, x + b\\\\
where :math:`a`, :math:`\\alpha`, :math:`m`, and :math:`b` are the real
constants and :math:`x` is the independent variable.
Parameters
----------
x: |array_like|
Independent variable.
a: float
value for constant :math:`a`
alpha: float
value for constant :math:`\\alpha`
m: float
value for slope :math:`m`
b: float
value for intercept :math:`b`
Returns
-------
y: |array_like|
dependent variables corresponding to ``x``
"""
exp_term = self._exponential.func(x, a, alpha)
lin_term = self._linear.func(x, m, b)
return exp_term + lin_term
@modify_docstring(append=AbstractFitFunction.func_err.__original_doc__)
def func_err(self, x, x_err=None, rety=False):
"""
Calculate dependent variable uncertainties :math:`\\delta y` for
dependent variables :math:`y=f(x)`.
.. math::
(\\delta y)^2 =&
\\left( a e^{\\alpha x}\\right)^2 \\left[
\\left( \\frac{\\delta a}{a} \\right)^2
+ (x \\, \\delta \\alpha)^2
+ (\\alpha \\, \\delta x)^2
\\right]\\\\
& + \\left(2 \\, a \\, \\alpha \\, m \\, e^{\\alpha x}\\right)
(\\delta x)^2\\\\
& + \\left[(
x \\, \\delta m)^2 + (\\delta b)^2 +(m \\, \\delta x)^2
\\right]
"""
x, x_err = self._check_func_err_params(x, x_err)
a, alpha, m, b = self.params
exp_y, exp_err = self._exponential(x, x_err=x_err, reterr=True)
lin_y, lin_err = self._linear(x, x_err=x_err, reterr=True)
err = exp_err**2 + lin_err**2
if x_err is not None:
blend_err = 2 * a * alpha * m * np.exp(alpha * x) * (x_err**2)
err += blend_err
err = np.sqrt(err)
return (err, exp_y + lin_y) if rety else err
class ExponentialPlusOffset(AbstractFitFunction):
"""
A sub-class of `AbstractFitFunction` to represent an exponential with a
constant offset.
.. math::
y =& f(x) = a \\, e^{\\alpha \\, x} + m \\, x + b\\\\
(\\delta y)^2 =&
\\left( a e^{\\alpha x}\\right)^2 \\left[
\\left( \\frac{\\delta a}{a} \\right)^2
+ (x \\, \\delta \\alpha)^2
+ (\\alpha \\, \\delta x)^2
\\right]
+ (\\delta b)^2
where :math:`a`, :math:`\\alpha`, and :math:`b` are the real constants to
be fitted and :math:`x` is the independent variable. :math:`\\delta a`,
:math:`\\delta \\alpha`, :math:`\\delta b`, and :math:`\\delta x` are the
respective uncertainties for :math:`a`, :math:`\\alpha`, and :math:`b`, and
:math:`x`.
"""
_param_names = ("a", "alpha", "b")
def __init__(
self,
params: Tuple[float, ...] = None,
param_errors: Tuple[float, ...] = None,
):
self._explin = ExponentialPlusLinear()
super().__init__(params=params, param_errors=param_errors)
def __str__(self):
return "f(x) = a exp(alpha x) + b"
@property
def latex_str(self) -> str:
return r"a \, \exp(\alpha x) + b"
@AbstractFitFunction.params.setter
def params(self, val) -> None:
AbstractFitFunction.params.fset(self, val)
self._explin.params = (
self.params.a,
self.params.alpha,
0.0,
self.params.b,
)
@AbstractFitFunction.param_errors.setter
def param_errors(self, val) -> None:
AbstractFitFunction.param_errors.fset(self, val)
self._explin.param_errors = (
self.param_errors.a,
self.param_errors.alpha,
0.0,
self.param_errors.b,
)
def func(self, x, a, alpha, b):
"""
The fit function, an exponential with a constant offset.
.. math::
f(x) = a \\, e^{\\alpha \\, x} + b\\\\
where :math:`a`, :math:`\\alpha`, and :math:`b` are the real constants
and :math:`x` is the independent variable.
Parameters
----------
x: |array_like|
Independent variable.
a: float
value for constant :math:`a`
alpha: float
value for constant :math:`\\alpha`
b: float
value for DC offset :math:`b`
Returns
-------
y: |array_like|