drux 0.4__tar.gz → 0.5__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.
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: drux
3
- Version: 0.4
3
+ Version: 0.5
4
4
  Summary: Drux: Drug Release Analysis Framework
5
5
  Home-page: https://github.com/openscilab/drux
6
- Download-URL: https://github.com/openscilab/drux/tarball/v0.4
6
+ Download-URL: https://github.com/openscilab/drux/tarball/v0.5
7
7
  Author: Drux Development Team
8
8
  Author-email: drux@openscilab.com
9
9
  License: MIT
@@ -37,6 +37,7 @@ License-File: LICENSE
37
37
  License-File: AUTHORS.md
38
38
  Requires-Dist: numpy>=1.21.0
39
39
  Requires-Dist: matplotlib>=3.2.2
40
+ Requires-Dist: scipy>=1.7.3
40
41
  Dynamic: author
41
42
  Dynamic: author-email
42
43
  Dynamic: classifier
@@ -56,7 +57,8 @@ Dynamic: summary
56
57
  <div align="center">
57
58
  <img src="https://github.com/openscilab/drux/raw/main/otherfiles/logo.png" width="350">
58
59
  <h1>Drux: Drug Release Analysis Framework</h1>
59
- <br/>
60
+ <p><i>Drux is dedicated to the memory of <a href="https://github.com/nazanin-nabi">Nazanin Nabinia</a>, one of its co-creators.</i></p>
61
+ <br/>
60
62
  <a href="https://badge.fury.io/py/drux"><img src="https://badge.fury.io/py/drux.svg" alt="PyPI version"></a>
61
63
  <a href="https://www.python.org/"><img src="https://img.shields.io/badge/built%20with-Python3-green.svg" alt="built with Python3"></a>
62
64
  <a href="https://codecov.io/gh/openscilab/drux"><img src="https://codecov.io/gh/openscilab/drux/branch/dev/graph/badge.svg?token=5O41J3XX2L"></a>
@@ -118,9 +120,9 @@ Drux is a Python-based framework for simulating drug release profiles using math
118
120
 
119
121
  ### PyPI
120
122
  - Check [Python Packaging User Guide](https://packaging.python.org/installing/)
121
- - Run `pip install drux==0.4`
123
+ - Run `pip install drux==0.5`
122
124
  ### Source code
123
- - Download [Version 0.4](https://github.com/openscilab/drux/archive/v0.4.zip) or [Latest Source](https://github.com/openscilab/drux/archive/dev.zip)
125
+ - Download [Version 0.5](https://github.com/openscilab/drux/archive/v0.5.zip) or [Latest Source](https://github.com/openscilab/drux/archive/dev.zip)
124
126
  - Run `pip install .`
125
127
 
126
128
  ## Supported Models
@@ -228,6 +230,54 @@ where:
228
230
  3. Transdermal Patches
229
231
  4. Injectable depots
230
232
 
233
+ ## Curve Fitting
234
+ The models above calculate a release profile from known parameters. The `CurveFit` class does the opposite operation. It calculates the parameters of a model from measured experimental data. `CurveFit` uses the non-linear least squares method. This method decreases the difference between the measured release and the calculated release.
235
+
236
+ `CurveFit` gives the quality of the fit as the coefficient of determination:
237
+
238
+ $$
239
+ R^2 = 1 - \frac{\sum_i \left(M_i - \hat{M}_i\right)^2}{\sum_i \left(M_i - \bar{M}\right)^2}
240
+ $$
241
+
242
+ where:
243
+ - $M_i (mg)$ is the measured drug release at time $t_i$
244
+ - $\hat{M}_i (mg)$ is the drug release that the model calculates at time $t_i$
245
+ - $\bar{M} (mg)$ is the mean value of the measured drug release
246
+
247
+ An $R^2$ value near 1 shows a good fit. A low value shows that the model does not describe the data correctly.
248
+
249
+ You can fit all the models above. This table gives the name and the parameters of each model:
250
+
251
+ | Model Name | Parameters |
252
+ |---------------| -------------------------- |
253
+ | `zero_order` | `M0`, `k0` |
254
+ | `first_order` | `M0`, `k` |
255
+ | `higuchi` | `D`, `c0`, `cs` |
256
+ | `weibull` | `M`, `a`, `b` |
257
+ | `hopfenberg` | `M`, `k0`, `c0`, `a0`, `n` |
258
+
259
+ The `fit` method starts from a value of 1 for each unknown parameter, and keeps all the parameters positive. If the result is not good, give your own values in the `initial_guess` and `bounds` arguments. These arguments contain only the unknown parameters. The `get_result` method gives the result of the last fit again.
260
+
261
+ The `fit` method returns a `FitResult` object, where:
262
+ - `model_name` is the name of the fitted model
263
+ - `parameters` is a dictionary of the known and the calculated parameter values
264
+ - `r_squared` is the fit's coefficient of determination
265
+ - `model` is a model object with the calculated parameters. You can simulate and plot this model.
266
+
267
+ ### Known Parameters
268
+ If you know the value of a parameter, give it in the `known_parameters` argument. Use the parameter names in the table above. `CurveFit` keeps these values constant and calculates only the other parameters.
269
+
270
+ ⚠️ All the parameters of a model cannot always be calculated from a release profile. Some models use a group of parameters only as one product or one ratio. Many different combinations of these parameters give the same value for this group. Thus, the fit has no unique solution, and the calculated values can be different from the true physical values. To prevent this problem, give at least **two** parameters of each group in the `known_parameters` argument. Two of the models have such a group:
271
+ - The Higuchi model uses $D$, $c_0$ and $c_s$ only in the product $D(2c_0 - c_s)c_s$. Give two of these three parameters, for example `known_parameters={"c0": 1, "cs": 0.5}`.
272
+ - The Hopfenberg model uses $k_0$, $c_0$ and $a_0$ only in the ratio $\frac{k_0}{c_0 a_0}$. Give two of these three parameters, and also the geometry factor $n$, for example `known_parameters={"c0": 0.0374, "a0": 3.51, "n": 2}`. Also, $n$ is always assumed to be known because the user should know the shape of the device.
273
+
274
+ ### Applications
275
+ 1. Analysis of dissolution test data
276
+ 2. Estimation of the release rate constants
277
+ 3. Selection of the correct model for an experiment
278
+ 4. Comparison of different formulations
279
+ 5. Quality control of production batches
280
+
231
281
  ## Usage
232
282
  ### Zero-Order Model
233
283
  ```python
@@ -276,6 +326,21 @@ model.plot(show=True)
276
326
  ```
277
327
  <img src="https://github.com/openscilab/drux/raw/main/otherfiles/hopfenberg_plot.png" alt="Hopfenberg Plot">
278
328
 
329
+ ### Curve Fitting
330
+
331
+ ```python
332
+ from drux import CurveFit
333
+ time = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
334
+ release_profile = [0, 0.35, 0.48, 0.57, 0.63, 0.69, 0.73, 0.77, 0.80, 0.83, 0.85]
335
+ fitter = CurveFit(model_name="weibull", time=time, release_profile=release_profile)
336
+ result = fitter.fit()
337
+ print(result.parameters)
338
+ print(result.r_squared)
339
+ result.model.simulate(duration=100, time_step=1)
340
+ result.model.plot(show=True)
341
+ ```
342
+ <img src="https://github.com/openscilab/drux/raw/main/otherfiles/curve_fit_plot.png" alt="Curve Fit Plot">
343
+
279
344
 
280
345
  ## Issues & bug reports
281
346
 
@@ -319,6 +384,15 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
319
384
  and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
320
385
 
321
386
  ## [Unreleased]
387
+ ## [0.5] - 2026-10-14
388
+ ### Added
389
+ - `CurveFit` class
390
+ - `CurveFit` class documentation
391
+ - `FitResult` class
392
+ ### Changed
393
+ - `_model_function` method refactored
394
+ - `_model_function` method renamed to `model_function`
395
+ - Dependencies structure modified
322
396
  ## [0.4] - 2026-05-18
323
397
  ### Added
324
398
  - Hopfenberg model
@@ -345,7 +419,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
345
419
  - Higuchi model
346
420
 
347
421
 
348
- [Unreleased]: https://github.com/openscilab/drux/compare/v0.4...dev
422
+ [Unreleased]: https://github.com/openscilab/drux/compare/v0.5...dev
423
+ [0.5]: https://github.com/openscilab/drux/compare/v0.4...v0.5
349
424
  [0.4]: https://github.com/openscilab/drux/compare/v0.3...v0.4
350
425
  [0.3]: https://github.com/openscilab/drux/compare/v0.2...v0.3
351
426
  [0.2]: https://github.com/openscilab/drux/compare/v0.1...v0.2
@@ -1,7 +1,8 @@
1
1
  <div align="center">
2
2
  <img src="https://github.com/openscilab/drux/raw/main/otherfiles/logo.png" width="350">
3
3
  <h1>Drux: Drug Release Analysis Framework</h1>
4
- <br/>
4
+ <p><i>Drux is dedicated to the memory of <a href="https://github.com/nazanin-nabi">Nazanin Nabinia</a>, one of its co-creators.</i></p>
5
+ <br/>
5
6
  <a href="https://badge.fury.io/py/drux"><img src="https://badge.fury.io/py/drux.svg" alt="PyPI version"></a>
6
7
  <a href="https://www.python.org/"><img src="https://img.shields.io/badge/built%20with-Python3-green.svg" alt="built with Python3"></a>
7
8
  <a href="https://codecov.io/gh/openscilab/drux"><img src="https://codecov.io/gh/openscilab/drux/branch/dev/graph/badge.svg?token=5O41J3XX2L"></a>
@@ -63,9 +64,9 @@ Drux is a Python-based framework for simulating drug release profiles using math
63
64
 
64
65
  ### PyPI
65
66
  - Check [Python Packaging User Guide](https://packaging.python.org/installing/)
66
- - Run `pip install drux==0.4`
67
+ - Run `pip install drux==0.5`
67
68
  ### Source code
68
- - Download [Version 0.4](https://github.com/openscilab/drux/archive/v0.4.zip) or [Latest Source](https://github.com/openscilab/drux/archive/dev.zip)
69
+ - Download [Version 0.5](https://github.com/openscilab/drux/archive/v0.5.zip) or [Latest Source](https://github.com/openscilab/drux/archive/dev.zip)
69
70
  - Run `pip install .`
70
71
 
71
72
  ## Supported Models
@@ -173,6 +174,54 @@ where:
173
174
  3. Transdermal Patches
174
175
  4. Injectable depots
175
176
 
177
+ ## Curve Fitting
178
+ The models above calculate a release profile from known parameters. The `CurveFit` class does the opposite operation. It calculates the parameters of a model from measured experimental data. `CurveFit` uses the non-linear least squares method. This method decreases the difference between the measured release and the calculated release.
179
+
180
+ `CurveFit` gives the quality of the fit as the coefficient of determination:
181
+
182
+ $$
183
+ R^2 = 1 - \frac{\sum_i \left(M_i - \hat{M}_i\right)^2}{\sum_i \left(M_i - \bar{M}\right)^2}
184
+ $$
185
+
186
+ where:
187
+ - $M_i (mg)$ is the measured drug release at time $t_i$
188
+ - $\hat{M}_i (mg)$ is the drug release that the model calculates at time $t_i$
189
+ - $\bar{M} (mg)$ is the mean value of the measured drug release
190
+
191
+ An $R^2$ value near 1 shows a good fit. A low value shows that the model does not describe the data correctly.
192
+
193
+ You can fit all the models above. This table gives the name and the parameters of each model:
194
+
195
+ | Model Name | Parameters |
196
+ |---------------| -------------------------- |
197
+ | `zero_order` | `M0`, `k0` |
198
+ | `first_order` | `M0`, `k` |
199
+ | `higuchi` | `D`, `c0`, `cs` |
200
+ | `weibull` | `M`, `a`, `b` |
201
+ | `hopfenberg` | `M`, `k0`, `c0`, `a0`, `n` |
202
+
203
+ The `fit` method starts from a value of 1 for each unknown parameter, and keeps all the parameters positive. If the result is not good, give your own values in the `initial_guess` and `bounds` arguments. These arguments contain only the unknown parameters. The `get_result` method gives the result of the last fit again.
204
+
205
+ The `fit` method returns a `FitResult` object, where:
206
+ - `model_name` is the name of the fitted model
207
+ - `parameters` is a dictionary of the known and the calculated parameter values
208
+ - `r_squared` is the fit's coefficient of determination
209
+ - `model` is a model object with the calculated parameters. You can simulate and plot this model.
210
+
211
+ ### Known Parameters
212
+ If you know the value of a parameter, give it in the `known_parameters` argument. Use the parameter names in the table above. `CurveFit` keeps these values constant and calculates only the other parameters.
213
+
214
+ ⚠️ All the parameters of a model cannot always be calculated from a release profile. Some models use a group of parameters only as one product or one ratio. Many different combinations of these parameters give the same value for this group. Thus, the fit has no unique solution, and the calculated values can be different from the true physical values. To prevent this problem, give at least **two** parameters of each group in the `known_parameters` argument. Two of the models have such a group:
215
+ - The Higuchi model uses $D$, $c_0$ and $c_s$ only in the product $D(2c_0 - c_s)c_s$. Give two of these three parameters, for example `known_parameters={"c0": 1, "cs": 0.5}`.
216
+ - The Hopfenberg model uses $k_0$, $c_0$ and $a_0$ only in the ratio $\frac{k_0}{c_0 a_0}$. Give two of these three parameters, and also the geometry factor $n$, for example `known_parameters={"c0": 0.0374, "a0": 3.51, "n": 2}`. Also, $n$ is always assumed to be known because the user should know the shape of the device.
217
+
218
+ ### Applications
219
+ 1. Analysis of dissolution test data
220
+ 2. Estimation of the release rate constants
221
+ 3. Selection of the correct model for an experiment
222
+ 4. Comparison of different formulations
223
+ 5. Quality control of production batches
224
+
176
225
  ## Usage
177
226
  ### Zero-Order Model
178
227
  ```python
@@ -221,6 +270,21 @@ model.plot(show=True)
221
270
  ```
222
271
  <img src="https://github.com/openscilab/drux/raw/main/otherfiles/hopfenberg_plot.png" alt="Hopfenberg Plot">
223
272
 
273
+ ### Curve Fitting
274
+
275
+ ```python
276
+ from drux import CurveFit
277
+ time = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
278
+ release_profile = [0, 0.35, 0.48, 0.57, 0.63, 0.69, 0.73, 0.77, 0.80, 0.83, 0.85]
279
+ fitter = CurveFit(model_name="weibull", time=time, release_profile=release_profile)
280
+ result = fitter.fit()
281
+ print(result.parameters)
282
+ print(result.r_squared)
283
+ result.model.simulate(duration=100, time_step=1)
284
+ result.model.plot(show=True)
285
+ ```
286
+ <img src="https://github.com/openscilab/drux/raw/main/otherfiles/curve_fit_plot.png" alt="Curve Fit Plot">
287
+
224
288
 
225
289
  ## Issues & bug reports
226
290
 
@@ -7,5 +7,6 @@ from .zero_order import ZeroOrderModel, ZeroOrderParameters
7
7
  from .first_order import FirstOrderModel, FirstOrderParameters
8
8
  from .weibull import WeibullModel, WeibullParameters
9
9
  from .hopfenberg import HopfenbergModel, HopfenbergParameters
10
+ from .curve_fit import CurveFit, FitResult
10
11
 
11
12
  __version__ = DRUX_VERSION
@@ -3,6 +3,7 @@
3
3
  import numpy as np
4
4
  import matplotlib.pyplot as plt
5
5
  from abc import ABC, abstractmethod
6
+ from dataclasses import asdict
6
7
  from typing import Any, Optional
7
8
 
8
9
  from .messages import (
@@ -23,12 +24,13 @@ class DrugReleaseModel(ABC):
23
24
  mathematical models of drug release from delivery systems.
24
25
 
25
26
  Subclasses should implement:
26
- - _model_function(): Core model equation
27
+ - model_function(): Core model equation, as a static method
27
28
  - _validate_parameters(): Parameter validation
28
29
  """
29
30
 
30
31
  def __init__(self):
31
32
  """Initialize the drug release model."""
33
+ self._parameters = None
32
34
  self._time_points = None
33
35
  self._release_profile = None
34
36
  self._plot_parameters = {
@@ -46,18 +48,25 @@ class DrugReleaseModel(ABC):
46
48
  """
47
49
  pass
48
50
 
51
+ @staticmethod
49
52
  @abstractmethod
50
- def _model_function(self, t: float) -> float:
53
+ def model_function(t: float, **parameters: Any) -> float:
51
54
  """
52
55
  Model function that calculates drug release profile over time.
53
56
 
57
+ Subclasses must implement this as a @staticmethod, computing the release
58
+ purely from time and explicit model parameters (no instance state), so the
59
+ formula is defined once and can be evaluated independently of a model instance.
60
+
54
61
  :param t: time point at which to calculate drug release
62
+ :param parameters: model parameters, matching the model's parameter dataclass fields
55
63
  """
56
64
  pass
57
65
 
58
66
  def _get_release_profile(self) -> np.ndarray:
59
67
  """Calculate the drug release profile over the specified time points."""
60
- return np.vectorize(self._model_function)(self._time_points)
68
+ parameters = asdict(self._parameters)
69
+ return np.vectorize(lambda t: self.model_function(t, **parameters))(self._time_points)
61
70
 
62
71
  def _validate_plot(self) -> tuple:
63
72
  """
@@ -0,0 +1,284 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Drux curve fitting utilities."""
3
+
4
+ import inspect
5
+ from dataclasses import dataclass
6
+ from math import isnan
7
+ from numbers import Real
8
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Type
9
+
10
+ import numpy as np
11
+ from scipy.optimize import curve_fit
12
+
13
+ from .base_model import DrugReleaseModel
14
+ from .first_order import FirstOrderModel
15
+ from .higuchi import HiguchiModel
16
+ from .hopfenberg import HopfenbergModel
17
+ from .weibull import WeibullModel
18
+ from .zero_order import ZeroOrderModel
19
+ from .params import DEFAULT_BOUNDS, DEFAULT_INITIAL_GUESS
20
+ from .messages import (
21
+ ERROR_UNKNOWN_MODEL,
22
+ ERROR_TIME_RELEASE_LENGTH_MISMATCH,
23
+ ERROR_INSUFFICIENT_DATA_POINTS,
24
+ ERROR_UNKNOWN_FIT_PARAMETER,
25
+ ERROR_UNKNOWN_FIT_ARGUMENT,
26
+ ERROR_KNOWN_FIT_ARGUMENT,
27
+ ERROR_MISSING_FIT_ARGUMENT,
28
+ ERROR_FIT_ARGUMENT_TYPE,
29
+ ERROR_INVALID_FIT_VALUE,
30
+ ERROR_INVALID_FIT_BOUNDS,
31
+ ERROR_FIT_BOUNDS_ORDER,
32
+ ERROR_FIT_GUESS_OUT_OF_BOUNDS,
33
+ ERROR_NO_FREE_PARAMETERS,
34
+ ERROR_NO_FIT_RESULT,
35
+ )
36
+
37
+ # Single point of registration mapping a model name to its class.
38
+ MODEL_CLASSES = {
39
+ "zero_order": ZeroOrderModel,
40
+ "first_order": FirstOrderModel,
41
+ "higuchi": HiguchiModel,
42
+ "weibull": WeibullModel,
43
+ "hopfenberg": HopfenbergModel,
44
+ }
45
+
46
+
47
+ def _fit_value(value: Any, parameter_name: str, argument_name: str) -> float:
48
+ """
49
+ Return a value of a fit argument as a float.
50
+
51
+ :param value: value given for the parameter
52
+ :param parameter_name: name of the parameter, used in the error message
53
+ :param argument_name: name of the fit argument, used in the error message
54
+ """
55
+ if not isinstance(value, Real) or isnan(value):
56
+ raise ValueError(ERROR_INVALID_FIT_VALUE.format(parameter_name=parameter_name, argument_name=argument_name))
57
+ return float(value)
58
+
59
+
60
+ def _model_parameter_names(model_class: Type[DrugReleaseModel]) -> List[str]:
61
+ """Return a model's parameter names, in declaration order, excluding time.
62
+
63
+ :param model_class: model class exposing a `model_function` signature
64
+ """
65
+ parameters = inspect.signature(model_class.model_function).parameters
66
+ return [name for name in parameters if name != "t"]
67
+
68
+
69
+ @dataclass
70
+ class FitResult:
71
+ """
72
+ Result of fitting a drug release model to experimental data.
73
+
74
+ Attributes:
75
+ model_name (str): name of the fitted model
76
+ parameters (Dict[str, float]): known and fitted parameter values, keyed by name
77
+ r_squared (float): coefficient of determination of the fit
78
+ model (DrugReleaseModel): model instance initialized with the fitted parameters
79
+ """
80
+
81
+ model_name: str
82
+ parameters: Dict[str, float]
83
+ r_squared: float
84
+ model: DrugReleaseModel
85
+
86
+
87
+ class CurveFit:
88
+ """Fit a registered drug release model to experimental time-series data."""
89
+
90
+ def __init__(
91
+ self,
92
+ model_name: str,
93
+ time: Sequence[float],
94
+ release_profile: Sequence[float],
95
+ known_parameters: Optional[Dict[str, float]] = None,
96
+ ) -> None:
97
+ """
98
+ Initialize the curve fitter.
99
+
100
+ :param model_name: name of a registered model (see `MODEL_CLASSES`)
101
+ :param time: time points of the experimental data (s)
102
+ :param release_profile: a sequence of measured drug release at each time point
103
+ :param known_parameters: parameter values to hold fixed instead of fitting
104
+ """
105
+ if model_name not in MODEL_CLASSES:
106
+ raise ValueError(ERROR_UNKNOWN_MODEL.format(model_name=model_name, available_models=sorted(MODEL_CLASSES)))
107
+
108
+ time = np.asarray(time, dtype=float)
109
+ release_profile = np.asarray(release_profile, dtype=float)
110
+ if time.shape != release_profile.shape:
111
+ raise ValueError(ERROR_TIME_RELEASE_LENGTH_MISMATCH)
112
+ if time.size < 2:
113
+ raise ValueError(ERROR_INSUFFICIENT_DATA_POINTS)
114
+
115
+ self._model_name = model_name
116
+ self._model_class = MODEL_CLASSES[model_name]
117
+ self._time = time
118
+ self._release_profile = release_profile
119
+ self._known_parameters = known_parameters or {}
120
+ self._parameter_names = _model_parameter_names(self._model_class)
121
+
122
+ unknown_keys = sorted(set(self._known_parameters) - set(self._parameter_names))
123
+ if unknown_keys:
124
+ raise ValueError(
125
+ ERROR_UNKNOWN_FIT_PARAMETER.format(unknown_keys=unknown_keys, model_name=model_name, parameter_names=self._parameter_names)
126
+ )
127
+
128
+ self._free_parameters = [p for p in self._parameter_names if p not in self._known_parameters]
129
+ if not self._free_parameters:
130
+ raise ValueError(ERROR_NO_FREE_PARAMETERS)
131
+
132
+ self._fit_result: Optional[FitResult] = None
133
+
134
+ def _merge_parameters(self, free_values: Sequence[float]) -> Dict[str, float]:
135
+ """Merge fitted values for free parameters with known fixed parameters.
136
+
137
+ :param free_values: fitted values in the model's declared free-parameter order
138
+ """
139
+ free_values = iter(free_values)
140
+ return {
141
+ name: self._known_parameters[name] if name in self._known_parameters else next(free_values)
142
+ for name in self._parameter_names
143
+ }
144
+
145
+ def _equation(self, t: np.ndarray, *free_values: Any) -> np.ndarray:
146
+ """Evaluate the model equation for a set of free parameter values.
147
+
148
+ :param t: time values where the model should be evaluated
149
+ :param free_values: free parameter values passed by the optimizer
150
+ """
151
+ parameters = self._merge_parameters(free_values)
152
+ return np.vectorize(lambda ti: self._model_class.model_function(ti, **parameters))(t)
153
+
154
+ def _validate_fit_argument(
155
+ self, values: Optional[Dict[str, Any]], argument_name: str) -> Optional[Dict[str, Any]]:
156
+ """
157
+ Check that a fit argument gives a value for every free parameter, and for no other parameter.
158
+
159
+ :param values: fit argument keyed by parameter name, or None to use the defaults
160
+ :param argument_name: name of the argument, used in the error messages
161
+ """
162
+ if values is None:
163
+ return None
164
+ if not isinstance(values, dict):
165
+ raise ValueError(ERROR_FIT_ARGUMENT_TYPE.format(argument_name=argument_name))
166
+
167
+ known_keys = sorted(set(values) & set(self._known_parameters))
168
+ if known_keys:
169
+ raise ValueError(ERROR_KNOWN_FIT_ARGUMENT.format(known_keys=known_keys, argument_name=argument_name))
170
+
171
+ unknown_keys = sorted(set(values) - set(self._free_parameters))
172
+ if unknown_keys:
173
+ raise ValueError(
174
+ ERROR_UNKNOWN_FIT_ARGUMENT.format(
175
+ unknown_keys=unknown_keys,
176
+ argument_name=argument_name,
177
+ model_name=self._model_name,
178
+ free_parameters=self._free_parameters)
179
+ )
180
+
181
+ missing_keys = [name for name in self._free_parameters if name not in values]
182
+ if missing_keys:
183
+ raise ValueError(
184
+ ERROR_MISSING_FIT_ARGUMENT.format(
185
+ missing_keys=missing_keys,
186
+ argument_name=argument_name,
187
+ free_parameters=self._free_parameters)
188
+ )
189
+ return values
190
+
191
+ def _parameter_bounds(self, bounds: Optional[Dict[str, Any]], name: str) -> Tuple[float, float]:
192
+ """
193
+ Return the validated `(lower, upper)` bounds of a single free parameter.
194
+
195
+ :param bounds: bounds keyed by parameter name, or None to use the defaults
196
+ :param name: name of the free parameter
197
+ """
198
+ if bounds is None:
199
+ return DEFAULT_BOUNDS
200
+
201
+ try:
202
+ low, high = bounds[name]
203
+ except (TypeError, ValueError):
204
+ raise ValueError(ERROR_INVALID_FIT_BOUNDS.format(parameter_name=name))
205
+
206
+ low = _fit_value(low, name, "bounds")
207
+ high = _fit_value(high, name, "bounds")
208
+ if low >= high:
209
+ raise ValueError(ERROR_FIT_BOUNDS_ORDER.format(parameter_name=name))
210
+ return low, high
211
+
212
+ def _parameter_guess(self, initial_guess: Optional[Dict[str, Any]], name: str, low: float, high: float) -> float:
213
+ """
214
+ Return the validated initial guess of a single free parameter.
215
+
216
+ :param initial_guess: initial guess keyed by parameter name, or None to use the default
217
+ :param name: name of the free parameter
218
+ :param low: validated lower bound of the parameter
219
+ :param high: validated upper bound of the parameter
220
+ """
221
+ # A default guess is kept inside the bounds, so that bounds stay usable on their own.
222
+ if initial_guess is None:
223
+ return min(max(DEFAULT_INITIAL_GUESS, low), high)
224
+
225
+ guess = _fit_value(initial_guess[name], name, "initial_guess")
226
+ if not low <= guess <= high:
227
+ raise ValueError(ERROR_FIT_GUESS_OUT_OF_BOUNDS.format(parameter_name=name))
228
+ return guess
229
+
230
+ def fit(
231
+ self,
232
+ initial_guess: Optional[Dict[str, float]] = None,
233
+ bounds: Optional[Dict[str, Tuple[float, float]]] = None,
234
+ ) -> FitResult:
235
+ """
236
+ Estimate the unknown parameters via non-linear least squares.
237
+
238
+ Both arguments are keyed by parameter name, so the caller does not need to know the
239
+ order in which the optimizer receives the free parameters. An argument that is given
240
+ must hold a value for every free parameter; omit the argument to use the defaults.
241
+
242
+ :param initial_guess: initial guess per free parameter, keyed by name (default: 1.0 for each)
243
+ :param bounds: `(lower, upper)` bounds per free parameter, keyed by name (default: (~0, inf))
244
+ """
245
+ initial_guess = self._validate_fit_argument(initial_guess, "initial_guess")
246
+ bounds = self._validate_fit_argument(bounds, "bounds")
247
+
248
+ lower, upper = zip(*(self._parameter_bounds(bounds, name) for name in self._free_parameters))
249
+ p0 = [
250
+ self._parameter_guess(initial_guess, name, low, high)
251
+ for name, low, high in zip(self._free_parameters, lower, upper)
252
+ ]
253
+
254
+ fitted_values, _ = curve_fit(
255
+ self._equation, self._time, self._release_profile, p0=p0, bounds=(list(lower), list(upper)), maxfev=10000
256
+ )
257
+ parameters = self._merge_parameters(fitted_values)
258
+
259
+ predicted = self._equation(self._time, *fitted_values)
260
+ residual_sum_of_squares = np.sum((self._release_profile - predicted) ** 2)
261
+ total_sum_of_squares = np.sum((self._release_profile - np.mean(self._release_profile)) ** 2)
262
+ r_squared = 1 - residual_sum_of_squares / total_sum_of_squares if total_sum_of_squares > 0 else 0.0
263
+
264
+ fit_result = FitResult(
265
+ model_name=self._model_name,
266
+ parameters=parameters,
267
+ r_squared=r_squared,
268
+ model=self._model_class(**parameters),
269
+ )
270
+ self._fit_result = fit_result
271
+ return fit_result
272
+
273
+ def get_result(self) -> FitResult:
274
+ """Return the most recent fit result."""
275
+ if self._fit_result is None:
276
+ raise ValueError(ERROR_NO_FIT_RESULT)
277
+ return self._fit_result
278
+
279
+ def __repr__(self) -> str:
280
+ """Return a string representation of the curve fitter."""
281
+ if self._fit_result is None:
282
+ return f"drux.CurveFit({self._model_name}, not fitted)"
283
+ params = ", ".join(f"{k}={v:.4f}" for k, v in self._fit_result.parameters.items())
284
+ return f"drux.CurveFit({self._model_name}: {params}, R^2={self._fit_result.r_squared:.4f})"
@@ -38,17 +38,17 @@ class FirstOrderModel(DrugReleaseModel):
38
38
  """Return a string representation of the First-Order model."""
39
39
  return f"drux.FirstOrderModel(k={self._parameters.k}, M0={self._parameters.M0})"
40
40
 
41
- def _model_function(self, t: float) -> float:
41
+ @staticmethod
42
+ def model_function(t: float, M0: float, k: float) -> float:
42
43
  """
43
44
  Calculate the drug release at time t using the first-order model.
44
45
 
45
46
  Formula:
46
47
  - M(t) = M0 * (1 - exp(-k * t))
47
48
  :param t: time (s)
49
+ :param M0: entire releasable amount of drug (the asymptotic maximum) (mg)
50
+ :param k: first-order release rate constant (1/s)
48
51
  """
49
- M0 = self._parameters.M0
50
- k = self._parameters.k
51
-
52
52
  Mt = M0 * (1 - exp(-k * t))
53
53
 
54
54
  return Mt
@@ -50,18 +50,18 @@ class HiguchiModel(DrugReleaseModel):
50
50
  f"c0={self._parameters.c0}, cs={self._parameters.cs})"
51
51
  )
52
52
 
53
- def _model_function(self, t: float) -> float:
53
+ @staticmethod
54
+ def model_function(t: float, D: float, c0: float, cs: float) -> float:
54
55
  """
55
56
  Calculate the drug release at time t using the Higuchi model.
56
57
 
57
58
  Formula:
58
59
  - General case: Mt = sqrt(D * c0 * (2*c0 - cs) * cs * t)
59
60
  :param t: time (s)
61
+ :param D: Drug diffusivity in the polymer carrier (cm^2/s)
62
+ :param c0: Initial drug concentration (mg/cm^3)
63
+ :param cs: Drug solubility in the polymer (mg/cm^3)
60
64
  """
61
- D = self._parameters.D
62
- c0 = self._parameters.c0
63
- cs = self._parameters.cs
64
-
65
65
  Mt = sqrt(D * (2 * c0 - cs) * cs * t)
66
66
 
67
67
  return Mt
@@ -56,7 +56,8 @@ class HopfenbergModel(DrugReleaseModel):
56
56
  f"n={self._parameters.n})"
57
57
  )
58
58
 
59
- def _model_function(self, t: float) -> float:
59
+ @staticmethod
60
+ def model_function(t: float, M: float, k0: float, c0: float, a0: float, n: int) -> float:
60
61
  """
61
62
  Calculate the fractional drug release at time t using the Hopfenberg model.
62
63
 
@@ -64,14 +65,13 @@ class HopfenbergModel(DrugReleaseModel):
64
65
  - Mt = M∞(1 - (1 - k0*t / (c0*a0))^n)
65
66
 
66
67
  :param t: time (s)
68
+ :param M: entire releasable amount of drug (normally M > 0) (mg)
69
+ :param k0: Erosion rate constant (mg/(mm^2·s))
70
+ :param c0: Initial drug concentration in the matrix (mg/mm^3)
71
+ :param a0: Initial radius or half-thickness of the device (mm)
72
+ :param n: Geometry factor (1=slab, 2=cylinder, 3=sphere)
67
73
  :return: drug release
68
74
  """
69
- M = self._parameters.M
70
- k0 = self._parameters.k0
71
- c0 = self._parameters.c0
72
- a0 = self._parameters.a0
73
- n = self._parameters.n
74
-
75
75
  inner_term = 1 - (k0 * t) / (c0 * a0)
76
76
 
77
77
  Mt = M * (1 - (inner_term**n))