3.1. Built-in Models¶
NLSQ provides commonly used mathematical models ready for curve fitting.
3.1.1. Available Models¶
Import models from nlsq.core.functions:
from nlsq.core.functions import (
exponential_decay,
gaussian,
lorentzian,
polynomial,
power_law,
sigmoid,
)
3.1.2. Exponential Decay¶
\[f(x) = a \cdot e^{-b \cdot x} + c\]
from nlsq import fit
from nlsq.core.functions import exponential_decay
# Parameters: amplitude, decay_rate, offset
popt, pcov = fit(exponential_decay, x, y, p0=[2.0, 0.5, 0.0])
a, b, c = popt
3.1.3. Gaussian (Normal Distribution)¶
\[f(x) = A \cdot e^{-\frac{(x - \mu)^2}{2\sigma^2}}\]
from nlsq.core.functions import gaussian
# Parameters: amplitude, center, width
popt, pcov = fit(gaussian, x, y, p0=[5.0, 0.0, 1.0])
amp, mu, sigma = popt
3.1.4. Lorentzian (Cauchy Distribution)¶
\[f(x) = \frac{A}{1 + \left(\frac{x - x_0}{\gamma}\right)^2}\]
from nlsq.core.functions import lorentzian
# Parameters: amplitude, center, half-width
popt, pcov = fit(lorentzian, x, y, p0=[5.0, 0.0, 1.0])
amp, x0, gamma = popt
3.1.5. Power Law¶
\[f(x) = a \cdot x^b\]
from nlsq.core.functions import power_law
# Parameters: coefficient, exponent
popt, pcov = fit(power_law, x, y, p0=[1.0, 2.0])
a, b = popt
3.1.6. Sigmoid (Logistic Function)¶
\[f(x) = \frac{L}{1 + e^{-k(x - x_0)}} + b\]
from nlsq.core.functions import sigmoid
# Parameters: max_value, midpoint, steepness, baseline
popt, pcov = fit(sigmoid, x, y, p0=[1.0, 0.0, 1.0, 0.0])
L, x0, k, b = popt
3.1.7. Polynomial¶
Polynomials of any degree:
import jax.numpy as jnp
# Define directly for curve fitting
def quadratic(x, a, b, c):
return a + b * x + c * x**2
popt, pcov = fit(quadratic, x, y, p0=[0, 1, 0])
3.1.8. Complete Example¶
import numpy as np
from nlsq import fit
from nlsq.core.functions import gaussian
# Generate data: Gaussian peak with noise
np.random.seed(42)
x = np.linspace(-5, 5, 100)
y_true = 3.0 * np.exp(-0.5 * ((x - 1.0) / 0.8) ** 2)
y = y_true + 0.2 * np.random.normal(size=len(x))
# Fit using built-in Gaussian
popt, pcov = fit(gaussian, x, y, p0=[2.5, 0.5, 1.0])
print("Fitted parameters:")
print(f" Amplitude: {popt[0]:.3f} (true: 3.0)")
print(f" Center: {popt[1]:.3f} (true: 1.0)")
print(f" Width: {popt[2]:.3f} (true: 0.8)")
3.1.9. Choosing the Right Model¶
Data Pattern |
Suggested Model |
|---|---|
Decreasing with asymptote |
|
Bell-shaped peak |
|
S-shaped curve |
|
Power relationship |
|
General trend |
|
Tips:
Gaussian peaks are narrower at the base
Lorentzian peaks have heavier tails
Use
exponential_decayfor radioactive decay, chemical reactionsUse
sigmoidfor growth curves, dose-response
3.1.10. Next Steps¶
Custom Models - Create your own models
Model Validation - Verify model correctness