orakel 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- orakel-1.0.0/LICENSE +165 -0
- orakel-1.0.0/PKG-INFO +70 -0
- orakel-1.0.0/README.md +48 -0
- orakel-1.0.0/pyproject.toml +28 -0
- orakel-1.0.0/src/orakel/__init__.py +29 -0
- orakel-1.0.0/src/orakel/metrics.py +46 -0
- orakel-1.0.0/src/orakel/predict.py +469 -0
orakel-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
orakel-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: orakel
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Orakel: A small library of regression models of interest to the life sciences.
|
|
5
|
+
Author-email: culpeo <culpeo@dismail.de>
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-Expression: LGPL-3.0-only
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy >=2.0
|
|
18
|
+
Requires-Dist: scipy >=1.13
|
|
19
|
+
Project-URL: Homepage, https://codeberg.org/culpeo/orakel
|
|
20
|
+
Project-URL: Source, https://codeberg.org/culpeo/orakel/src/branch/main/src/orakel
|
|
21
|
+
|
|
22
|
+
# Orakel
|
|
23
|
+
|
|
24
|
+
Orakel is a small Python library of regression models based on NumPy and Scipy.
|
|
25
|
+
|
|
26
|
+
## Purpose
|
|
27
|
+
|
|
28
|
+
The analysis and evaluation of experimental data are often influenced by artefacts or signal noise. Yet, the observed processes can often be described by mathematical models. Orakel provides implementations of various regression models that are suited for analysing enzyme kinetics and biological processes, such as bacterial growth.
|
|
29
|
+
|
|
30
|
+
## Use
|
|
31
|
+
|
|
32
|
+
Orakel is intended to be used within a script or processing pipeline.
|
|
33
|
+
|
|
34
|
+
The following functions are implemented:
|
|
35
|
+
|
|
36
|
+
- `exponential_decay`: exponential decay with optional non-zero asymptote (controlled by boolean flag `non_zero_asymptote`)
|
|
37
|
+
- `double_exponential_decay`: double exponential decay with optional non-zero asymptote (controlled by boolean flag `non_zero_asymptote`)
|
|
38
|
+
- `gompertz`: Gompertz' generalised logistic function
|
|
39
|
+
- `richards`: Richards generalised logistic function
|
|
40
|
+
- `michaelis_menten`: the Michaelis-Menten function
|
|
41
|
+
- `schnell_mendoza`: explicit form of the Michaelis-Menten equation using Lambert's W function
|
|
42
|
+
- `power_function`: the power function
|
|
43
|
+
|
|
44
|
+
For modelling and predictions based on these functions, all except the Schnell-Mendoza function can be used within the class `NonlinearRegression`. The Schnell-Mendoza function is not implemented as fitting-class, as its numerical complexity makes it particularly difficult to find suitable model parameters automatically without tight constraints.
|
|
45
|
+
|
|
46
|
+
After initialising the class (set `non_zero_asymptote=True`, to allow for exponential decays with non-zero asymptote), the model is fitted using `fit(x, y)`. The initial parameters and reasonable limits are estimated for each sample automatically. Predictions with the fitted model are made using `predict(x_new)`. As an example, a model for exponential decay is fitted and used for predictions:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import numpy as np
|
|
50
|
+
|
|
51
|
+
from orakel.predict import exponential_decay, NonlinearRegression
|
|
52
|
+
|
|
53
|
+
x = np.linspace(0, 3)
|
|
54
|
+
y_true = exponential_decay(x, 1, 1.5)
|
|
55
|
+
|
|
56
|
+
rng = np.random.default_rng()
|
|
57
|
+
noise = rng.normal(0, .05, y_true.shape)
|
|
58
|
+
y_sample = y_true + noise
|
|
59
|
+
|
|
60
|
+
model = NonlinearRegression('exponential_decay')
|
|
61
|
+
model.fit(x, y_sample)
|
|
62
|
+
y_pred = model.predict(x)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
While the array for the independent variable must be one-dimensional, the dependent variable can be of shape (n_samples, n_points). The array returned by predict is always of this shape.
|
|
66
|
+
|
|
67
|
+
## Further information
|
|
68
|
+
|
|
69
|
+
Orakel is primarily the product of personal interest and an attempt to document findings. For this reason, it cannot be considered stable. However, if you find it helpful, you are welcome to use it.
|
|
70
|
+
|
orakel-1.0.0/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Orakel
|
|
2
|
+
|
|
3
|
+
Orakel is a small Python library of regression models based on NumPy and Scipy.
|
|
4
|
+
|
|
5
|
+
## Purpose
|
|
6
|
+
|
|
7
|
+
The analysis and evaluation of experimental data are often influenced by artefacts or signal noise. Yet, the observed processes can often be described by mathematical models. Orakel provides implementations of various regression models that are suited for analysing enzyme kinetics and biological processes, such as bacterial growth.
|
|
8
|
+
|
|
9
|
+
## Use
|
|
10
|
+
|
|
11
|
+
Orakel is intended to be used within a script or processing pipeline.
|
|
12
|
+
|
|
13
|
+
The following functions are implemented:
|
|
14
|
+
|
|
15
|
+
- `exponential_decay`: exponential decay with optional non-zero asymptote (controlled by boolean flag `non_zero_asymptote`)
|
|
16
|
+
- `double_exponential_decay`: double exponential decay with optional non-zero asymptote (controlled by boolean flag `non_zero_asymptote`)
|
|
17
|
+
- `gompertz`: Gompertz' generalised logistic function
|
|
18
|
+
- `richards`: Richards generalised logistic function
|
|
19
|
+
- `michaelis_menten`: the Michaelis-Menten function
|
|
20
|
+
- `schnell_mendoza`: explicit form of the Michaelis-Menten equation using Lambert's W function
|
|
21
|
+
- `power_function`: the power function
|
|
22
|
+
|
|
23
|
+
For modelling and predictions based on these functions, all except the Schnell-Mendoza function can be used within the class `NonlinearRegression`. The Schnell-Mendoza function is not implemented as fitting-class, as its numerical complexity makes it particularly difficult to find suitable model parameters automatically without tight constraints.
|
|
24
|
+
|
|
25
|
+
After initialising the class (set `non_zero_asymptote=True`, to allow for exponential decays with non-zero asymptote), the model is fitted using `fit(x, y)`. The initial parameters and reasonable limits are estimated for each sample automatically. Predictions with the fitted model are made using `predict(x_new)`. As an example, a model for exponential decay is fitted and used for predictions:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import numpy as np
|
|
29
|
+
|
|
30
|
+
from orakel.predict import exponential_decay, NonlinearRegression
|
|
31
|
+
|
|
32
|
+
x = np.linspace(0, 3)
|
|
33
|
+
y_true = exponential_decay(x, 1, 1.5)
|
|
34
|
+
|
|
35
|
+
rng = np.random.default_rng()
|
|
36
|
+
noise = rng.normal(0, .05, y_true.shape)
|
|
37
|
+
y_sample = y_true + noise
|
|
38
|
+
|
|
39
|
+
model = NonlinearRegression('exponential_decay')
|
|
40
|
+
model.fit(x, y_sample)
|
|
41
|
+
y_pred = model.predict(x)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
While the array for the independent variable must be one-dimensional, the dependent variable can be of shape (n_samples, n_points). The array returned by predict is always of this shape.
|
|
45
|
+
|
|
46
|
+
## Further information
|
|
47
|
+
|
|
48
|
+
Orakel is primarily the product of personal interest and an attempt to document findings. For this reason, it cannot be considered stable. However, if you find it helpful, you are welcome to use it.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["flit_core >=3.11,<4"]
|
|
3
|
+
build-backend = "flit_core.buildapi"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "orakel"
|
|
7
|
+
dynamic = ["version", "description"]
|
|
8
|
+
authors = [{name="culpeo", email="culpeo@dismail.de"}]
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "LGPL-3.0-only"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Intended Audience :: Science/Research",
|
|
18
|
+
"Topic :: Scientific/Engineering",
|
|
19
|
+
"Topic :: Software Development :: Libraries",
|
|
20
|
+
]
|
|
21
|
+
dependencies = [
|
|
22
|
+
"numpy >=2.0",
|
|
23
|
+
"scipy >=1.13"
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://codeberg.org/culpeo/orakel"
|
|
28
|
+
Source = "https://codeberg.org/culpeo/orakel/src/branch/main/src/orakel"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Orakel: A small library of regression models of interest to the life sciences.
|
|
3
|
+
|
|
4
|
+
Subpackages
|
|
5
|
+
-----------
|
|
6
|
+
predict
|
|
7
|
+
The model functions and the wrapper class to perform non-linear regression.
|
|
8
|
+
metrics
|
|
9
|
+
Auxiliary functions to calculate coefficients.
|
|
10
|
+
|
|
11
|
+
Metadata
|
|
12
|
+
--------
|
|
13
|
+
__author__
|
|
14
|
+
The author's name.
|
|
15
|
+
__copyright__
|
|
16
|
+
The copyright notice.
|
|
17
|
+
__license__
|
|
18
|
+
The SPDX license identifier of the license valid for Orakel.
|
|
19
|
+
__version__
|
|
20
|
+
Orakel version string.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
__author__ = 'culpeo'
|
|
24
|
+
__copyright__ = 'Copyright (C) 2025 culpeo <culpeo@dismail.de>'
|
|
25
|
+
__license__ = 'LGPL-3.0-only'
|
|
26
|
+
__version__ = '1.0.0'
|
|
27
|
+
|
|
28
|
+
from . import predict
|
|
29
|
+
from . import metrics
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Orakel is a library providing different regression models.
|
|
2
|
+
# Copyright (C) 2025 culpeo <culpeo@dismail.de>
|
|
3
|
+
|
|
4
|
+
# This program is free software: you can redistribute it and/or modify it
|
|
5
|
+
# under the terms of the GNU Lesser General Public License as published by
|
|
6
|
+
# the Free Software Foundation, either version 3 of the License, or (at your
|
|
7
|
+
# option) any later version.
|
|
8
|
+
|
|
9
|
+
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
10
|
+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
11
|
+
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
|
|
12
|
+
# for more details.
|
|
13
|
+
|
|
14
|
+
# You should have received a copy of the GNU Lesser General Public License
|
|
15
|
+
# along with this program. If not, see https://www.gnu.org/licenses/.
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
def calculate_r2(y_true: np.ndarray, y_pred: np.ndarray):
|
|
20
|
+
"""Calculate the coefficient of determination R2."""
|
|
21
|
+
ss_res = np.sum((y_true - y_pred) ** 2)
|
|
22
|
+
ss_tot = np.sum((y_true - y_true.mean()) ** 2)
|
|
23
|
+
return 1 - ss_res / ss_tot if ss_tot != 0 else np.nan
|
|
24
|
+
|
|
25
|
+
def calculate_aic(y_true: np.ndarray, y_pred: np.ndarray, n_params: int):
|
|
26
|
+
"""
|
|
27
|
+
Calculate Akaike information criterion (AIC).
|
|
28
|
+
|
|
29
|
+
Assuming Gaussian-distributed errors, the AIC can be simplified using the
|
|
30
|
+
squared sum of the residuals to n * ln(ss_res / n) + 2p.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
y_true : array-like with one dimension
|
|
35
|
+
The observed values.
|
|
36
|
+
y_pred : array-like with one dimension
|
|
37
|
+
The predicted values.
|
|
38
|
+
|
|
39
|
+
Returns
|
|
40
|
+
-------
|
|
41
|
+
aic : float
|
|
42
|
+
The Akaike information criterion.
|
|
43
|
+
"""
|
|
44
|
+
n_points = len(y_true)
|
|
45
|
+
ss_res = np.sum((y_true - y_pred) ** 2)
|
|
46
|
+
return n_points * np.log(ss_res / n_points) + 2 * n_params
|
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
# Orakel is a library providing different regression models.
|
|
2
|
+
# Copyright (C) 2025 culpeo <culpeo@dismail.de>
|
|
3
|
+
|
|
4
|
+
# This program is free software: you can redistribute it and/or modify it
|
|
5
|
+
# under the terms of the GNU Lesser General Public License as published by
|
|
6
|
+
# the Free Software Foundation, either version 3 of the License, or (at your
|
|
7
|
+
# option) any later version.
|
|
8
|
+
|
|
9
|
+
# This program is distributed in the hope that it will be useful, but WITHOUT
|
|
10
|
+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
11
|
+
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
|
|
12
|
+
# for more details.
|
|
13
|
+
|
|
14
|
+
# You should have received a copy of the GNU Lesser General Public License
|
|
15
|
+
# along with this program. If not, see https://www.gnu.org/licenses/.
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from scipy.optimize import curve_fit
|
|
21
|
+
from scipy.special import lambertw
|
|
22
|
+
|
|
23
|
+
from orakel.metrics import calculate_aic, calculate_r2
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def exponential_decay(x: np.ndarray, a: float, k: float, b: float = 0.0):
|
|
27
|
+
"""
|
|
28
|
+
Exponential decay with optional non-zero asymptote.
|
|
29
|
+
|
|
30
|
+
y = b + (a - b) * exp(-k * x)
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
x : np.ndarray
|
|
35
|
+
The independent variable, for example the time.
|
|
36
|
+
a : float
|
|
37
|
+
Initial value at x = 0.
|
|
38
|
+
k : float
|
|
39
|
+
Rate constant.
|
|
40
|
+
b : float, optional
|
|
41
|
+
Lower limit of function (asymptote, by default zero).
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
y : np.ndarray
|
|
46
|
+
The dependent variable.
|
|
47
|
+
"""
|
|
48
|
+
return b + (a - b) * np.exp(-k * x)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _specify_exponential_decay(
|
|
52
|
+
x: np.ndarray, y: np.ndarray, non_zero_asymptote: bool = False
|
|
53
|
+
):
|
|
54
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
55
|
+
a = y[0]
|
|
56
|
+
b = y[-1] if non_zero_asymptote else 0.0
|
|
57
|
+
k = (a - b) / x.max() if x.max() != 0 else 1.0
|
|
58
|
+
guessed_params = (a, k, b) if non_zero_asymptote else (a, k)
|
|
59
|
+
lower = (0.0, ) * len(guessed_params)
|
|
60
|
+
upper = (a * 2, np.inf, a) if non_zero_asymptote else (a * 2, np.inf)
|
|
61
|
+
param_limits = (lower, upper)
|
|
62
|
+
return guessed_params, param_limits
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def double_exponential_decay(
|
|
66
|
+
x: np.ndarray, a1: float, k1: float, a2: float, k2: float, b: float = 0.0
|
|
67
|
+
):
|
|
68
|
+
"""
|
|
69
|
+
Double exponential decay with optional non-zero asymptote.
|
|
70
|
+
|
|
71
|
+
b + (a1 - a2) * exp(-k1 * x) + (a2 - b) * exp(-k2 * x)
|
|
72
|
+
|
|
73
|
+
Parameters
|
|
74
|
+
----------
|
|
75
|
+
x : np.ndarray
|
|
76
|
+
The independent variable, for example the time.
|
|
77
|
+
a1 : float
|
|
78
|
+
Initial value at x = 0.
|
|
79
|
+
k1 : float
|
|
80
|
+
Rate constant of the first phase of exponential decay.
|
|
81
|
+
a2 : float
|
|
82
|
+
Initial value of the second phase of exponential decay.
|
|
83
|
+
k2 : float
|
|
84
|
+
Rate constant of the second phase of exponential decay.
|
|
85
|
+
b : float, optional
|
|
86
|
+
Lower limit of function (asymptote, by default zero).
|
|
87
|
+
|
|
88
|
+
Returns
|
|
89
|
+
-------
|
|
90
|
+
y : np.ndarray
|
|
91
|
+
The dependent variable.
|
|
92
|
+
"""
|
|
93
|
+
return b + (a1 - a2) * np.exp(-k1 * x) + (a2 - b) * np.exp(-k2 * x)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _specify_double_exponential_decay(
|
|
97
|
+
x: np.ndarray, y: np.ndarray, non_zero_asymptote: bool = False
|
|
98
|
+
):
|
|
99
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
100
|
+
a1 = y[0]
|
|
101
|
+
b = y[-1] if non_zero_asymptote else 0.0
|
|
102
|
+
k1 = (a1 - b) / x.max() if x.max() != 0 else 1.0
|
|
103
|
+
a2 = a1 / 2
|
|
104
|
+
k2 = k1 / 10
|
|
105
|
+
if non_zero_asymptote:
|
|
106
|
+
guessed_params = (a1, k1, a2, k2, b)
|
|
107
|
+
upper = (a1 * 2, np.inf, a1, np.inf, a1)
|
|
108
|
+
else:
|
|
109
|
+
guessed_params = (a1, k1, a2, k2)
|
|
110
|
+
upper = (a1 * 2, np.inf, a1, np.inf)
|
|
111
|
+
lower = (0.0, ) * len(guessed_params)
|
|
112
|
+
param_limits = (lower, upper)
|
|
113
|
+
return guessed_params, param_limits
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def gompertz(x: np.ndarray, a: float, ku: float, xi: float):
|
|
117
|
+
"""
|
|
118
|
+
Gompertz' generalised logistic function.
|
|
119
|
+
|
|
120
|
+
y = a * exp(-exp(-(exp(1) * ku * (x - xi) / a)))
|
|
121
|
+
|
|
122
|
+
Special case of Richards generalised logistic function with three or four
|
|
123
|
+
parameters and the inflection occurring at 36.79 % of the upper asymptote
|
|
124
|
+
after Benjamin Gompertz. Re-parameterised by Tjørve and Tjørve 2017.
|
|
125
|
+
|
|
126
|
+
Parameters
|
|
127
|
+
----------
|
|
128
|
+
a : float
|
|
129
|
+
Upper limit of function (upper asymptote).
|
|
130
|
+
ku : float
|
|
131
|
+
Absolute maximum growth rate (slope at inflection point).
|
|
132
|
+
xi : float
|
|
133
|
+
Abscissa of inflection point.
|
|
134
|
+
|
|
135
|
+
Returns
|
|
136
|
+
-------
|
|
137
|
+
y : np.ndarray
|
|
138
|
+
The dependent variable.
|
|
139
|
+
|
|
140
|
+
References
|
|
141
|
+
----------
|
|
142
|
+
Tjørve KMC, Tjørve E. The use of Gompertz models in growth analyses, and
|
|
143
|
+
new Gompertz-model approach: An addition to the Unified-Richards family.
|
|
144
|
+
PLoS One. 2017;12(6):e0178691. doi:10.1371/journal.pone.0178691
|
|
145
|
+
"""
|
|
146
|
+
# a * np.exp(-np.exp(-np.exp(1) * ku * (x - xi)))
|
|
147
|
+
return a * np.exp(-np.exp(-(np.exp(1) * ku * (x - xi) / a)))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _specify_gompertz(x: np.ndarray, y: np.ndarray):
|
|
151
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
152
|
+
a = y.max()
|
|
153
|
+
ku = (a - y.min()) / x.max() if x.max() != 0 else 1.0
|
|
154
|
+
xi = x[np.argmin(abs(y - a * 0.368))]
|
|
155
|
+
guessed_params = (a, ku, xi)
|
|
156
|
+
param_limits = (0.0, (a * 2, np.inf, x.max()))
|
|
157
|
+
return guessed_params, param_limits
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def richards(x: np.ndarray, a: float, d: float, ku: float, xi: float):
|
|
161
|
+
"""
|
|
162
|
+
Richards generalised logistic function.
|
|
163
|
+
|
|
164
|
+
Unified variant of Richards generalised logistic function with four
|
|
165
|
+
parameters, re-parameterised by Tjørve and Tjørve 2010.
|
|
166
|
+
|
|
167
|
+
Parameters
|
|
168
|
+
----------
|
|
169
|
+
a : float
|
|
170
|
+
Upper limit of function (upper asymptote)
|
|
171
|
+
d : float
|
|
172
|
+
Proportion of upper asymptote at inflection; a * (d ** (1 / (1 - d)))
|
|
173
|
+
ku : float
|
|
174
|
+
Relative maximum growth rate (slope at inflection point); Ku = ku * a
|
|
175
|
+
xi : float
|
|
176
|
+
Abscissa of inflection point
|
|
177
|
+
|
|
178
|
+
Returns
|
|
179
|
+
-------
|
|
180
|
+
y : np.ndarray
|
|
181
|
+
The dependent variable.
|
|
182
|
+
|
|
183
|
+
References
|
|
184
|
+
----------
|
|
185
|
+
Tjørve E, Tjørve KMC. A unified approach to the Richards-model family for
|
|
186
|
+
use in growth analyses: Why we need only two model forms. Journal of
|
|
187
|
+
Theoretical Biology. 2010;267(3):417-425. doi:10.1016/j.jtbi.2010.09.008
|
|
188
|
+
"""
|
|
189
|
+
exponent = -ku * (x - xi) / d ** (d / (1 - d))
|
|
190
|
+
base = 1 + (d - 1) * np.exp(exponent)
|
|
191
|
+
return a * base ** (1 / (1 - d))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _specify_richards(x: np.ndarray, y: np.ndarray):
|
|
195
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
196
|
+
a = y.max()
|
|
197
|
+
d = 1.5
|
|
198
|
+
ku = (a - y.min()) / x.max() / a if x.max() != 0 else 1.0 / a
|
|
199
|
+
xi = x[np.argmin(abs(y - a / 2))]
|
|
200
|
+
guessed_params = (a, d, ku, xi)
|
|
201
|
+
param_limits = (0.0, (a * 2, 2, np.inf, x.max()))
|
|
202
|
+
return guessed_params, param_limits
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def michaelis_menten(x: np.ndarray, km: float, vmax: float):
|
|
206
|
+
"""
|
|
207
|
+
The Michaelis-Menten equation v = V_max * x / (K_M + x).
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
x : array-like with one dimension
|
|
212
|
+
Substrate concentration (the independent variable).
|
|
213
|
+
km : float
|
|
214
|
+
Substrate concentration at half-maximal velocity (Michaelis constant).
|
|
215
|
+
vmax : float
|
|
216
|
+
Maximum reaction rate or velocity.
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
y : np.ndarray
|
|
221
|
+
Reaction rate for given substrate concentration(s).
|
|
222
|
+
"""
|
|
223
|
+
return vmax * x / (km + x)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _specify_michaelis_menten(x: np.ndarray, y: np.ndarray):
|
|
227
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
228
|
+
vmax = y.max()
|
|
229
|
+
km = x[np.argmin(abs(y - vmax / 2))]
|
|
230
|
+
guessed_params = (km, vmax)
|
|
231
|
+
param_limits = (1e-6, (x.max(), vmax * 2))
|
|
232
|
+
return guessed_params, param_limits
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def schnell_mendoza(t: np.ndarray, s0: float, km: float, vmax: float):
|
|
236
|
+
"""
|
|
237
|
+
Explicit form of the Michaelis-Menten equation using Lambert's W function.
|
|
238
|
+
|
|
239
|
+
Defined with the substrate s, the substrate concentration at half-maximal
|
|
240
|
+
velocity K_M, and the maximum reaction rate or velocity V_max:
|
|
241
|
+
|
|
242
|
+
s = K_M * W((s0 / K_M) * exp((s0 - V_max * t) / K_M))
|
|
243
|
+
|
|
244
|
+
Parameters
|
|
245
|
+
----------
|
|
246
|
+
t : np.ndarray
|
|
247
|
+
Time (the independent variable).
|
|
248
|
+
s0 : float
|
|
249
|
+
Initial substrate concentration (i. e., at t = 0).
|
|
250
|
+
km : float
|
|
251
|
+
Substrate concentration at half-maximal velocity (Michaelis constant).
|
|
252
|
+
vmax : float
|
|
253
|
+
Maximum reaction rate or velocity.
|
|
254
|
+
|
|
255
|
+
Returns
|
|
256
|
+
-------
|
|
257
|
+
s : np.ndarray
|
|
258
|
+
Substrate concentration at a given time.
|
|
259
|
+
|
|
260
|
+
References
|
|
261
|
+
----------
|
|
262
|
+
1. Schnell S, Mendoza C. Closed form solution for time-dependent enzyme
|
|
263
|
+
kinetics. Journal of Theoretical Biology. 1997;187(2):207-212.
|
|
264
|
+
doi:10.1006/jtbi.1997.0425
|
|
265
|
+
2. Goudar CT, Harris SK, McInerney MJ, Suflita JM. Progress curve analysis
|
|
266
|
+
for enzyme and microbial kinetic reactions using explicit solutions
|
|
267
|
+
based on the Lambert W function. Journal of Microbiological Methods.
|
|
268
|
+
2004;59(3):317-326. doi:10.1016/j.mimet.2004.06.013
|
|
269
|
+
"""
|
|
270
|
+
arg = (s0 / km) * np.exp((s0 - vmax * t) / km)
|
|
271
|
+
return km * lambertw(arg).real
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def power_function(x: np.ndarray, a: float, b: float):
|
|
275
|
+
"""
|
|
276
|
+
The power function y = a * x ** b.
|
|
277
|
+
|
|
278
|
+
Parameters
|
|
279
|
+
----------
|
|
280
|
+
x : np.ndarray
|
|
281
|
+
The independent variable, for example the time.
|
|
282
|
+
a : float
|
|
283
|
+
Coefficient. Acts as a multiplier.
|
|
284
|
+
b : float
|
|
285
|
+
Power. The exponent of the power function.
|
|
286
|
+
|
|
287
|
+
Returns
|
|
288
|
+
-------
|
|
289
|
+
y : np.ndarray
|
|
290
|
+
The dependent variable.
|
|
291
|
+
"""
|
|
292
|
+
return a * x ** b
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _specify_power_function(x: np.ndarray, y: np.ndarray):
|
|
296
|
+
"""Guess parameters and specify limits for non-linear regression."""
|
|
297
|
+
x1, x2 = np.percentile(x, [5.0, 95.0])
|
|
298
|
+
y1, y2 = np.percentile(y, [5.0, 95.0])
|
|
299
|
+
b = (np.log(y2) - np.log(y1)) / (np.log(x2) - np.log(x1))
|
|
300
|
+
a = np.exp(np.log(y1) - b * np.log(x1))
|
|
301
|
+
guessed_params = (a, b)
|
|
302
|
+
param_limits = ((0.0, -5.0), (a * 5, 5.0))
|
|
303
|
+
return guessed_params, param_limits
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@dataclass
|
|
307
|
+
class ModelSpecification:
|
|
308
|
+
"""Specification for a non-linear model."""
|
|
309
|
+
function: callable
|
|
310
|
+
auto_params: callable
|
|
311
|
+
|
|
312
|
+
MODELS = {
|
|
313
|
+
'double_exponential_decay': ModelSpecification(
|
|
314
|
+
function=double_exponential_decay,
|
|
315
|
+
auto_params=_specify_double_exponential_decay
|
|
316
|
+
),
|
|
317
|
+
'exponential_decay': ModelSpecification(
|
|
318
|
+
function=exponential_decay,
|
|
319
|
+
auto_params=_specify_exponential_decay
|
|
320
|
+
),
|
|
321
|
+
'gompertz': ModelSpecification(
|
|
322
|
+
function=gompertz,
|
|
323
|
+
auto_params=_specify_gompertz
|
|
324
|
+
),
|
|
325
|
+
'michaelis_menten': ModelSpecification(
|
|
326
|
+
function=michaelis_menten,
|
|
327
|
+
auto_params=_specify_michaelis_menten
|
|
328
|
+
),
|
|
329
|
+
'power_function': ModelSpecification(
|
|
330
|
+
function=power_function,
|
|
331
|
+
auto_params=_specify_power_function
|
|
332
|
+
),
|
|
333
|
+
'richards': ModelSpecification(
|
|
334
|
+
function=richards,
|
|
335
|
+
auto_params=_specify_richards
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
class NonlinearRegression:
|
|
341
|
+
"""
|
|
342
|
+
Perform regression analysis with the selected non-linear model.
|
|
343
|
+
|
|
344
|
+
Parameters
|
|
345
|
+
----------
|
|
346
|
+
model_name : str
|
|
347
|
+
The regression model to be used.
|
|
348
|
+
**model_kwargs : additional, model-specific arguments
|
|
349
|
+
Optional arguments for the selected model (e. g., flag for model of
|
|
350
|
+
exponential decay non_zero_asymptote=True).
|
|
351
|
+
|
|
352
|
+
Raises
|
|
353
|
+
------
|
|
354
|
+
ValueError
|
|
355
|
+
Raises an error if the selected model is not available.
|
|
356
|
+
|
|
357
|
+
Returns
|
|
358
|
+
-------
|
|
359
|
+
self : object
|
|
360
|
+
"""
|
|
361
|
+
|
|
362
|
+
def __init__(self, model_name: str, **model_kwargs):
|
|
363
|
+
if model_name not in MODELS:
|
|
364
|
+
raise ValueError(f'Select a model from: {list(MODELS.keys())}.')
|
|
365
|
+
self._model = MODELS[model_name]
|
|
366
|
+
self._model_kwargs = model_kwargs
|
|
367
|
+
self.params_ = None
|
|
368
|
+
self.scores_ = None
|
|
369
|
+
|
|
370
|
+
@property
|
|
371
|
+
def description(self):
|
|
372
|
+
"""Give docstring of used function."""
|
|
373
|
+
return self._model.function.__doc__
|
|
374
|
+
|
|
375
|
+
def fit(self, x: np.ndarray, y: np.ndarray):
|
|
376
|
+
"""
|
|
377
|
+
Estimate parameters of the selected model.
|
|
378
|
+
|
|
379
|
+
Parameters
|
|
380
|
+
----------
|
|
381
|
+
x : array-like with one dimension
|
|
382
|
+
Independent variable (e. g., time)
|
|
383
|
+
y : array-like of shape (n_samples, n_points)
|
|
384
|
+
Dependent variable (e. g., measured signal)
|
|
385
|
+
|
|
386
|
+
Returns
|
|
387
|
+
-------
|
|
388
|
+
self : object
|
|
389
|
+
Regression model describing relationship between x and y with the
|
|
390
|
+
optimal parameters and scores as attributes:
|
|
391
|
+
|
|
392
|
+
params_ : np.ndarray of shape (n_samples, n_params)
|
|
393
|
+
scores_ : np.ndarray of shape (n_samples, 2)
|
|
394
|
+
Scores of model and estimation: coefficient of determination
|
|
395
|
+
and Akaike information criterion (AIC).
|
|
396
|
+
"""
|
|
397
|
+
if x.ndim != 1:
|
|
398
|
+
raise ValueError('x must be a one-dimensional array.')
|
|
399
|
+
if y.ndim == 1:
|
|
400
|
+
y = y[np.newaxis, :]
|
|
401
|
+
|
|
402
|
+
n_samples, n_points = y.shape
|
|
403
|
+
if n_points != x.size:
|
|
404
|
+
raise ValueError(f'y has {n_points} points but x has {x.size}.')
|
|
405
|
+
|
|
406
|
+
# Cache values before loop
|
|
407
|
+
model = self._model.function
|
|
408
|
+
model_kwargs = self._model_kwargs
|
|
409
|
+
specify_model = self._model.auto_params
|
|
410
|
+
|
|
411
|
+
# Determine number of model parameters
|
|
412
|
+
guessed_params, _ = specify_model(x, y[0], **model_kwargs)
|
|
413
|
+
n_params = len(guessed_params)
|
|
414
|
+
|
|
415
|
+
params = np.empty((n_samples, n_params), dtype=float)
|
|
416
|
+
scores = np.empty((n_samples, 2), dtype=float)
|
|
417
|
+
|
|
418
|
+
for i in range(n_samples):
|
|
419
|
+
yi = y[i]
|
|
420
|
+
|
|
421
|
+
# Fit model based on initial estimate and model-specific limits
|
|
422
|
+
guessed_params, param_limits = specify_model(x, yi, **model_kwargs)
|
|
423
|
+
try:
|
|
424
|
+
opt_params, _ = curve_fit(
|
|
425
|
+
model,
|
|
426
|
+
x,
|
|
427
|
+
yi,
|
|
428
|
+
p0=guessed_params,
|
|
429
|
+
bounds=param_limits
|
|
430
|
+
)
|
|
431
|
+
except ValueError:
|
|
432
|
+
params[i] = np.nan
|
|
433
|
+
scores[i] = np.nan
|
|
434
|
+
continue
|
|
435
|
+
|
|
436
|
+
params[i] = opt_params
|
|
437
|
+
y_pred = model(x, *opt_params)
|
|
438
|
+
scores[i] = (
|
|
439
|
+
calculate_r2(yi, y_pred), calculate_aic(yi, y_pred, n_params)
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
self.params_ = params
|
|
443
|
+
self.scores_ = scores
|
|
444
|
+
|
|
445
|
+
return self
|
|
446
|
+
|
|
447
|
+
def predict(self, x: np.ndarray):
|
|
448
|
+
"""
|
|
449
|
+
Predict y for a given x using the trained model.
|
|
450
|
+
|
|
451
|
+
Parameters
|
|
452
|
+
----------
|
|
453
|
+
x : array-like with one dimension
|
|
454
|
+
Independent variable (e. g., time)
|
|
455
|
+
|
|
456
|
+
Returns
|
|
457
|
+
-------
|
|
458
|
+
y : np.ndarray of shape (n_samples, n_points)
|
|
459
|
+
Estimated dependent variable (e. g., measured signal)
|
|
460
|
+
"""
|
|
461
|
+
if self.params_ is None:
|
|
462
|
+
raise RuntimeError('Model has not been fitted yet.')
|
|
463
|
+
if x.ndim != 1:
|
|
464
|
+
raise ValueError('x must be an one-dimensional array.')
|
|
465
|
+
|
|
466
|
+
params = (
|
|
467
|
+
self.params_[:, p][:, None] for p in range(self.params_.shape[1])
|
|
468
|
+
)
|
|
469
|
+
return self._model.function(x, *params)
|