summaryrefslogtreecommitdiff
path: root/silx/math/fit/fittheory.py
blob: 17441ac01d8e350ce1d8021362900280dddf6315 (plain)
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
# coding: utf-8
#/*##########################################################################
#
# Copyright (c) 2004-2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
########################################################################### */
"""
This module defines the :class:`FitTheory` object that is used by
:class:`silx.math.fit.FitManager` to define fit functions and background
models.
"""

__authors__ = ["P. Knobel"]
__license__ = "MIT"
__date__ = "09/08/2016"


class FitTheory(object):
    """This class defines a fit theory, which consists of:

        - a model function, the actual function to be fitted
        - parameters names
        - an estimation function, that return the estimated initial parameters
          that serve as input for :func:`silx.math.fit.leastsq`
        - an optional configuration function, that can be used to modify
          configuration parameters to alter the behavior of the fit function
          and the estimation function
        - an optional derivative function, that replaces the default model
          derivative used in :func:`silx.math.fit.leastsq`
    """
    def __init__(self, function, parameters,
                 estimate=None, configure=None, derivative=None,
                 description=None, pymca_legacy=False, is_background=False):
        """
        :param function function: Actual function. See documentation for
            :attr:`function`.
        :param list[str] parameters: List of parameter names for the function.
            See documentation for :attr:`parameters`.
        :param function estimate: Optional estimation function.
            See documentation for :attr:`estimate`
        :param function configure: Optional configuration function.
            See documentation for :attr:`configure`
        :param function derivative: Optional custom derivative function.
            See documentation for :attr:`derivative`
        :param str description: Optional description string.
            See documentation for :attr:`description`
        :param bool pymca_legacy: Flag to indicate that the theory is a PyMca
            legacy theory. See documentation for :attr:`pymca_legacy`
        :param bool is_background: Flag to indicate that the theory is a
            background theory. This has implications regarding the function's
            signature, as explained in the documentation for :attr:`function`.
        """
        self.function = function
        """Regular fit functions must have the signature *f(x, \*params) -> y*,
        where *x* is a 1D array of values for the independent variable,
        *params* are the parameters to be fitted and *y* is the output array
        that we want to have the best fit to a series of data points.

        Background functions used by :class:`FitManager` must have a slightly
        different signature: *f(x, y0, \*params) -> bg*, where *y0* is the
        array of original data points and *bg* is the background signal that
        we want to subtract from the data array prior to fitting the regular
        fit function.

        The number of parameters must be the same as in :attr:`parameters`, or
        a multiple of this number if the function is defined as a sum of a
        variable number of base functions and if :attr:`estimate` is designed
        to be able to estimate the number of needed base functions.
        """

        self.parameters = parameters
        """List of parameters names.

        This list can contain the minimum number of parameters, if the
        function takes a variable number of parameters,
        and if the estimation function is responsible for finding the number
        of required parameters """

        self.estimate = estimate
        """The estimation function should have the following signature::

            f(x, y) -> (estimated_param, constraints)

        Parameters:

            - ``x`` is a sequence of values for the independent variable
            - ``y`` is a sequence of the same length as ``x`` containing the
              data to be fitted

        Return values:

            - ``estimated_param`` is a sequence of estimated fit parameters to
              be used as initial values for an iterative fit.
            - ``constraints`` is a sequence of shape *(n, 3)*, where *n* is the
              number of estimated parameters, containing the constraints for each
              parameter to be fitted. See :func:`silx.math.fit.leastsq` for more
              explanations about constraints."""
        if estimate is None:
            self.estimate = self.default_estimate

        self.configure = configure
        """The optional configuration function must conform to the signature
        ``f(**kw) -> dict`` (i.e it must accept any named argument and
        return a dictionary).
        It can be used to modify configuration parameters to alter the
        behavior of the fit function and the estimation function."""

        self.derivative = derivative
        """The optional derivative function must conform to the signature
        ``model_deriv(xdata, parameters, index)``, where parameters is a
        sequence with the current values of the fitting parameters, index is
        the fitting parameter index for which the the derivative has to be
        provided in the supplied array of xdata points."""

        self.description = description
        """Optional description string for this particular fit theory."""

        self.pymca_legacy = pymca_legacy
        """This attribute can be set to *True* to indicate that the theory
        is a PyMca legacy theory.

        This tells :mod:`silx.math.fit.fitmanager` that the signature of
        the estimate function is::

            f(x, y, bg, xscaling, yscaling) -> (estimated_param, constraints)
        """

        self.is_background = is_background
        """Flag to indicate that the theory is background theory.

        A background function is an secondary function that needs to be added
        to the main fit function to better fit the original data.
        If this flag is set to *True*, modules using this theory are informed
        that :attr:`function` has the signature *f(x, y0, \*params) -> bg*,
        instead of the usual fit function signature."""

    def default_estimate(self, x=None, y=None, bg=None):
        """Default estimate function. Return an array of *ones* as the
        initial estimated parameters, and set all constraints to zero
        (FREE)"""
        estimated_parameters = [1. for _ in self.parameters]
        estimated_constraints = [[0, 0, 0] for _ in self.parameters]
        return estimated_parameters, estimated_constraints