fitle 0.1.0__py3-none-any.whl

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.
fitle/pdfs.py ADDED
@@ -0,0 +1,207 @@
1
+ """pdfs.py
2
+ =========
3
+ Pre-built probability density functions for fitting.
4
+
5
+ This module provides commonly used PDFs as Model factories. Each
6
+ function returns a normalized probability density that can be used
7
+ directly with cost functions.
8
+
9
+ Available PDFs:
10
+
11
+ - **gaussian**: Normal distribution
12
+ - **exponential**: Exponential decay
13
+ - **crystalball**: Crystal Ball function (Gaussian core + power-law tail)
14
+
15
+ Example::
16
+
17
+ from fitle import Param, fit, Cost
18
+ from fitle.pdfs import gaussian
19
+
20
+ # Default parameters (auto-created)
21
+ model = gaussian()
22
+
23
+ # Custom parameters
24
+ mu = Param("mu")(5.0)(0, 10) # Bounded mean
25
+ sigma = Param.positive("sigma")(1.0)
26
+ model = gaussian(mu, sigma)
27
+
28
+ result = fit(model | Cost.NLL(data))
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import numpy as np
33
+ from .model import Model, INPUT, const, _indecise, Reduction
34
+ from .param import Param, _Param, index
35
+ import math
36
+
37
+ SQRT2PI = np.sqrt(2 * np.pi)
38
+
39
+ def _erf(x):
40
+ """Wrapper for math.erf that Numba can compile."""
41
+ return math.erf(x)
42
+ _erf.__name__ = 'erf'
43
+
44
+
45
+ def gaussian(mu: _Param | float | None = None, sigma: _Param | float | None = None) -> Model:
46
+ """Create a Gaussian (normal) probability density function.
47
+
48
+ Returns the normalized PDF: ``(1 / (sigma * sqrt(2*pi))) * np.exp(-0.5 * ((x - mu) / sigma)^2)``
49
+
50
+ Parameters
51
+ ----------
52
+ mu : _Param | float | None, optional
53
+ Mean of the distribution. If None, creates ``Param("mu")``.
54
+ sigma : _Param | float | None, optional
55
+ Standard deviation. If None, creates ``Param.positive("sigma")``.
56
+
57
+ Returns
58
+ -------
59
+ Model
60
+ A normalized Gaussian PDF model.
61
+
62
+ Examples
63
+ --------
64
+ >>> g = gaussian() # Auto-creates mu and sigma parameters
65
+ >>> g = gaussian(Param("mean")(5.0), Param.positive("width")(1.0))
66
+ """
67
+ mu = mu if mu is not None else Param("mu")
68
+ sigma = sigma if sigma is not None else Param.positive("sigma")
69
+
70
+ norm = 1 / (sigma * SQRT2PI)
71
+ arg = -0.5 * ((INPUT - mu) / sigma) ** 2
72
+ return norm * Model(np.exp, [arg])
73
+
74
+
75
+ def exponential(
76
+ tau: _Param | float | None = None,
77
+ start: float | None = None,
78
+ end: float | None = None
79
+ ) -> Model:
80
+ """Create an exponential probability density function.
81
+
82
+ If start and end are provided, returns a truncated exponential PDF
83
+ normalized over [start, end]:
84
+ ``(1/tau) * exp(-(x-start)/tau) / (1 - exp(-(end-start)/tau))``
85
+
86
+ Otherwise returns the standard exponential PDF over [0, inf):
87
+ ``(1/tau) * exp(-x/tau)``
88
+
89
+ Parameters
90
+ ----------
91
+ tau : _Param | float | None, optional
92
+ Decay constant (mean lifetime). If None, creates ``Param.positive("tau")``.
93
+ start : float, optional
94
+ Left boundary for truncated exponential.
95
+ end : float, optional
96
+ Right boundary for truncated exponential.
97
+
98
+ Returns
99
+ -------
100
+ Model
101
+ A normalized exponential PDF model.
102
+
103
+ Examples
104
+ --------
105
+ >>> e = exponential() # Standard exponential over [0, inf)
106
+ >>> e = exponential(tau=+Param, start=0, end=10) # Truncated
107
+ """
108
+ tau = tau if tau is not None else Param.positive('tau')
109
+ if start is not None and end is not None:
110
+ norm = 1 - np.exp(-(end - start) / tau)
111
+ return (1 / tau) * np.exp(-(INPUT - start) / tau) / norm
112
+ return (1 / tau) * np.exp(-INPUT / tau)
113
+
114
+ def crystalball(alpha, n, mu, sigma):
115
+ """
116
+ Crystal Ball PDF.
117
+
118
+ alpha > 0 : transition point in units of sigma (typical: 0.5-5)
119
+ n > 1 : tail power (typical: 1.5-10)
120
+ mu : mean
121
+ sigma : width
122
+ """
123
+ import warnings
124
+
125
+ # Warn about extreme parameter values that may cause numerical issues
126
+ def _check_param(p, name, min_val, max_val):
127
+ if isinstance(p, _Param):
128
+ val = p.start if p.start is not None else p.value
129
+ if val is not None and (val < min_val or val > max_val):
130
+ warnings.warn(
131
+ f"crystalball {name}={val} is outside typical range [{min_val}, {max_val}]. "
132
+ f"Extreme values may cause numerical issues.",
133
+ UserWarning, stacklevel=2
134
+ )
135
+
136
+ _check_param(alpha, 'alpha', 0.1, 10)
137
+ _check_param(n, 'n', 1.01, 50)
138
+
139
+ x = INPUT
140
+ t = (x - mu) / sigma # (x - μ)/σ
141
+
142
+ pref = n / alpha # n/|α|
143
+ B = pref - alpha # n/|α| - |α|
144
+ C = n / (alpha * (n - 1)) * np.exp(-0.5 * alpha**2)
145
+ D = np.sqrt(0.5*np.pi) * (1 + Model(_erf, [alpha/np.sqrt(2)]))
146
+
147
+ N = 1.0 / (sigma * (C + D))
148
+
149
+ # --- core Gaussian part ---
150
+ core = np.exp(-0.5 * t**2)
151
+
152
+ # --- tail: computed fully in log-space ---
153
+ # logA = n*np.log(n/|α|) - α²/2
154
+ # Clamp B - t to avoid log of negative values (np.where evaluates both branches)
155
+ logA = n * np.log(pref) - 0.5 * alpha**2
156
+ log_tail = logA - n * np.log(np.maximum(B - t, 1e-10))
157
+ tail = np.exp(log_tail)
158
+
159
+ # --- piecewise: Gaussian for t > -α, tail otherwise ---
160
+ return np.where(t > -alpha, N * core, N * tail)
161
+
162
+
163
+ def convolve(
164
+ d_x: np.ndarray,
165
+ c: np.ndarray,
166
+ mass_mother: _Param | float,
167
+ mu: _Param | float,
168
+ sigma: _Param | float,
169
+ idx: _Param | None = None
170
+ ) -> Model:
171
+ """Create a convolution of a kernel with coefficient weights.
172
+
173
+ Computes a weighted sum of Gaussians at different centers,
174
+ useful for modeling resolution effects or detector response.
175
+ Returns a normalized PDF that integrates to 1.
176
+
177
+ Parameters
178
+ ----------
179
+ d_x : ndarray
180
+ Center positions for each Gaussian component.
181
+ c : ndarray
182
+ Weights (coefficients) for each Gaussian component. Will be
183
+ normalized to sum to 1 internally.
184
+ mass_mother : _Param | float
185
+ Reference mass for the shift.
186
+ mu : _Param | float
187
+ Mean offset parameter.
188
+ sigma : _Param | float
189
+ Common width for all Gaussian components.
190
+ idx : Param, optional
191
+ INDEX parameter for the sum. If None, creates one automatically.
192
+
193
+ Returns
194
+ -------
195
+ Model
196
+ A normalized PDF model (integrates to 1).
197
+ """
198
+ i = index(len(c)) if not idx else idx
199
+ # Pre-normalize weights to sum to 1
200
+ c_normalized = np.asarray(c) / np.sum(c)
201
+ w = _indecise(const(c_normalized), i)
202
+ centers = _indecise(const(d_x), i)
203
+ shifted_x = INPUT + mass_mother - mu
204
+ g = gaussian(centers, sigma) % shifted_x
205
+ weighted = w * g
206
+ ret = Reduction(weighted, i)
207
+ return ret