Core API¶
The core module contains the main PSpline class that implements penalized B-spline smoothing.
PSpline Class¶
Univariate penalised B-spline smoother.
fit ¶
fit(
*, xl: float | None = None, xr: float | None = None
) -> PSpline
Fit the P-spline model.
For Gaussian family, solves the penalized normal equations directly. For Poisson/Binomial families, uses IRLS (eq. 2.21–2.22).
Parameters:
-
xl(float, default:None) –Left boundary of the domain. Defaults to min(x).
-
xr(float, default:None) –Right boundary of the domain. Defaults to max(x).
Returns:
-
PSpline–The fitted spline object.
Source code in src/psplines/core.py
predict ¶
predict(
x_new: ArrayLike,
*,
return_se: bool = False,
se_method: str = "analytic",
scale: str = "response",
n_boot: int = 5000,
seed: int | None = None,
n_jobs: int = 1,
ci_prob: float = 0.95,
) -> NDArray | tuple[NDArray, ...]
Predict fitted values with optional uncertainty.
For derivatives, use :meth:derivative instead.
Parameters:
-
x_new(array - like) –Points at which to evaluate the spline.
-
return_se(bool, default:False) –Whether to return standard errors.
-
se_method(str, default:"analytic") –Method for computing uncertainty: - 'analytic': delta-method SE -> (fhat, se) or (mu_hat, lower, upper) - 'bootstrap': parametric bootstrap SEs -> (fhat, se) - 'bayes': posterior mean + credible interval -> (mean, lower, upper)
-
scale(str, default:"response") –Scale for predictions: - 'response': predictions on response scale (mu for Poisson, pi for Binomial) - 'link': predictions on linear predictor scale (eta) For Gaussian, both are identical.
-
n_boot(int, default:5000) –Number of bootstrap replicates (for bootstrap method).
-
seed(int, default:None) –Random seed (for bootstrap method).
-
n_jobs(int, default:1) –Number of parallel jobs (for bootstrap method).
-
ci_prob(float, default:0.95) –Probability for confidence/credible interval.
Returns:
-
NDArray or tuple–Predictions, optionally with uncertainty estimates. For GLM with return_se=True and scale="response": returns (mu_hat, lower, upper) with CI on response scale. For scale="link" with return_se=True: returns (eta_hat, se_eta).
Source code in src/psplines/core.py
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 | |
derivative ¶
derivative(
x_new: ArrayLike,
*,
deriv_order: int = 1,
return_se: bool = False,
se_method: str = "analytic",
n_boot: int = 5000,
seed: int | None = None,
n_jobs: int = 1,
ci_prob: float = 0.95,
) -> NDArray | tuple[NDArray, ...]
Compute k-th derivative of the fitted spline.
Parameters:
-
x_new(array - like) –Points at which to evaluate the derivative.
-
deriv_order(int, default:1) –Order of derivative to compute.
-
return_se(bool, default:False) –Whether to return standard errors.
-
se_method(str, default:"analytic") –Method for computing uncertainty: - 'analytic': delta-method SE -> (fhat, se) - 'bootstrap': parametric bootstrap SEs -> (fhat, se) - 'bayes': posterior mean + credible interval -> (mean, lower, upper)
-
n_boot(int, default:5000) –Number of bootstrap replicates (for bootstrap method).
-
seed(int, default:None) –Random seed (for bootstrap method).
-
n_jobs(int, default:1) –Number of parallel jobs (for bootstrap method).
-
ci_prob(float, default:0.95) –Probability for confidence/credible interval.
Returns:
-
NDArray or tuple–Derivative values, optionally with standard errors.
Source code in src/psplines/core.py
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 | |
bayes_fit ¶
bayes_fit(
a: float = 2.0,
b: float = 0.1,
c: float = 2.0,
d: float = 1.0,
draws: int = 2000,
tune: int = 2000,
chains: int = 4,
cores: int = 4,
target_accept: float = 0.9,
random_seed: int | None = None,
adaptive: bool = False,
nuts_sampler: str = "pymc",
) -> Any
Fit the P-spline model using Bayesian inference via PyMC.
Two modes are available:
Standard (default, adaptive=False) — implements the Bayesian P-spline of Eilers & Marx §3.5 / Lang & Brezger (2003) with a single penalty parameter:
.. math::
\lambda \sim \text{Gamma}(a, b), \quad
\alpha \mid \lambda \sim N(0, (\lambda D'D + \epsilon I)^{-1}), \quad
\sigma \sim \text{InverseGamma}(c, d)
Adaptive (adaptive=True) — uses one penalty parameter per row of the difference matrix, allowing spatially varying smoothness (similar to §8.8):
.. math::
\lambda_j \sim \text{Gamma}(a, b), \quad
\alpha \mid \lambda \sim N(0, (D' \Lambda D + \epsilon I)^{-1})
Requires the bayes optional dependencies: pip install psplines[bayes]
Parameters:
-
a(float, default:2.0) –Shape parameter for the Gamma prior on penalty lambda(s).
-
b(float, default:0.1) –Rate parameter for the Gamma prior on penalty lambda(s).
-
c(float, default:2.0) –Shape parameter for the InverseGamma prior on sigma.
-
d(float, default:1.0) –Scale parameter for the InverseGamma prior on sigma.
-
draws(int, default:2000) –Number of MCMC posterior draws per chain.
-
tune(int, default:2000) –Number of tuning (warmup) steps per chain.
-
chains(int, default:4) –Number of MCMC chains.
-
cores(int, default:4) –Number of CPU cores for parallel sampling.
-
target_accept(float, default:0.9) –Target acceptance rate for the NUTS sampler.
-
random_seed(int, default:None) –Random seed for reproducibility.
-
adaptive(bool, default:False) –If False, use a single scalar penalty lambda (§3.5). If True, use per-difference lambdas for spatially adaptive smoothing (§8.8).
-
nuts_sampler(str, default:'pymc') –NUTS sampler backend passed to
pymc.sample()."pymc"(default) uses the built-in PyTensor/C backend."nutpie"compiles the model once via numba and samples chains in parallel threads, which is significantly faster for multi-chain runs. Requiresnutpieto be installed (pip install psplines[nutpie]).
Returns:
-
InferenceData–The posterior trace object.
Source code in src/psplines/core.py
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 | |
plot_lam_trace ¶
Plot trace and marginal posterior for each lambda_j.
plot_alpha_trace ¶
Plot trace and marginal posterior for alpha coefficients.
plot_posterior ¶
Plot posterior
Source code in src/psplines/core.py
Usage Examples¶
Basic Usage¶
import numpy as np
from psplines import PSpline, ShapeConstraint, SlopeZeroConstraint
# Generate data
x = np.linspace(0, 1, 50)
y = np.sin(2 * np.pi * x) + 0.1 * np.random.randn(50)
# Create and fit spline
spline = PSpline(x, y, nseg=20, lambda_=1.0)
spline.fit()
# Make predictions
x_new = np.linspace(0, 1, 100)
y_pred = spline.predict(x_new)
With Uncertainty Quantification¶
# Analytical standard errors
y_pred, se = spline.predict(x_new, return_se=True)
# Bootstrap confidence intervals
y_pred, se_boot = spline.predict(x_new, return_se=True,
se_method="bootstrap", n_boot=1000)
Derivative Computation¶
# First derivative
dy_dx = spline.derivative(x_new, deriv_order=1)
# Second derivative with uncertainty
d2y_dx2, se = spline.derivative(x_new, deriv_order=2, return_se=True)
With Observation Weights¶
# Heteroscedastic weights (trust right side of data more)
weights = 1.0 + 5.0 * x
spline = PSpline(x, y, weights=weights)
spline.fit()
# Missing data via zero weights
weights = np.ones_like(x)
weights[20:30] = 0.0 # mark observations 20-29 as missing
spline = PSpline(x, y, weights=weights)
spline.fit() # penalty interpolates smoothly through the gap
Poisson P-Spline (Count Data)¶
# Smooth count data with log link
years = np.arange(1851, 1963, dtype=float)
counts = ... # annual event counts
spline = PSpline(years, counts, nseg=20, lambda_=100, family="poisson")
spline.fit()
# Predictions are positive (response scale)
x_new = np.linspace(1851, 1962, 200)
mu_pred = spline.predict(x_new) # scale="response" is default
# Confidence intervals on response scale (asymmetric, always positive)
mu_hat, lower, upper = spline.predict(x_new, return_se=True)
# Linear predictor (log scale)
eta = spline.predict(x_new, scale="link")
Shape-Constrained Smoothing¶
# Monotone increasing fit
x = np.linspace(0, 5, 60)
y = np.log(x + 1) + 0.2 * np.random.randn(60)
spline = PSpline(x, y, nseg=20, lambda_=1.0,
shape=[ShapeConstraint(type="increasing")])
spline.fit()
# All first differences of the fitted coefficients will be ≥ 0
y_pred = spline.predict(np.linspace(0, 5, 200))
# Concave fit
spline = PSpline(x, y, nseg=20, lambda_=1.0,
shape=[ShapeConstraint(type="concave")])
spline.fit()
# Multiple constraints: increasing AND concave
spline = PSpline(x, y, nseg=20, lambda_=1.0,
shape=[ShapeConstraint(type="increasing"), ShapeConstraint(type="concave")])
spline.fit()
# Selective domain constraint (monotone only for x ≤ 3)
spline = PSpline(x, y, nseg=20, lambda_=1.0,
shape=[ShapeConstraint(type="increasing",
domain=(float(x.min()), 3.0))])
spline.fit()
Variable Penalty (Exponential Weights)¶
# Heavier smoothing toward the right boundary (γ > 0)
spline = PSpline(x, y, nseg=20, lambda_=1.0, penalty_gamma=5.0)
spline.fit()
Adaptive Penalty (Spatially Varying Smoothness)¶
# Nonparametric adaptive smoothing — the penalty weights are
# estimated from the data via a secondary B-spline basis.
spline = PSpline(x, y, nseg=20, lambda_=1.0,
adaptive=True, adaptive_nseg=10,
adaptive_lambda=100.0)
spline.fit()
# The estimated per-difference weights are stored in:
print(spline._adaptive_weights)
Poisson with Exposure Offsets¶
# Rate modeling: mu = exp(B*alpha) * exposure
exposure = ... # population at risk
spline = PSpline(x, counts, family="poisson", offset=np.log(exposure))
spline.fit()
Binomial P-Spline (Binary/Proportion Data)¶
# Bernoulli response (y in {0, 1})
spline = PSpline(age, presence, nseg=15, lambda_=10, family="binomial")
spline.fit()
# Fitted probabilities are in [0, 1]
pi_hat = spline.predict(age_new)
# Grouped binomial (y successes out of t trials)
spline = PSpline(x, successes, family="binomial", trials=trials_vec)
spline.fit()
Density Estimation¶
from psplines import density_estimate
# Smooth density from raw data (AIC-optimal lambda)
result = density_estimate(raw_data, bins=100, penalty_order=3)
# result.density integrates to ~1
# result.grid contains evaluation points
# result.pspline is the underlying fitted PSpline
Bayesian Inference¶
# Standard Bayesian P-spline (single λ, §3.5 of Eilers & Marx 2021)
trace = spline.bayes_fit(draws=2000, tune=1000)
# Adaptive Bayesian P-spline (per-difference λ_j, §8.8)
trace = spline.bayes_fit(draws=2000, tune=1000, adaptive=True)
# Get posterior credible intervals (works with either mode)
mean, lower, upper = spline.predict(x_new, se_method="bayes")
Model Parameters¶
Basis Function Parameters¶
-
nseg: Number of B-spline segments- Controls the flexibility of the basis
- More segments = more flexible fit
- Typical values: 10-50
-
degree: Degree of B-spline basis functions- Controls local smoothness
- Higher degree = smoother derivatives
- Typical values: 1-4 (3 is most common)
Penalty Parameters¶
-
lambda_: Smoothing parameter- Controls the trade-off between fit and smoothness
- Higher values = smoother fits
- Can be selected automatically
-
penalty_order: Order of the difference penalty- 1: Penalizes first differences (rough penalty on slopes)
- 2: Penalizes second differences (rough penalty on curvature)
- 3: Penalizes third differences (rough penalty on jerk)
Observation Weights¶
weights: Optional array of non-negative observation weights- Same length as
xandy - Replaces the normal equations with weighted form: \((B'WB + \lambda D'D)\alpha = B'Wy\)
- Higher weights give more influence to those observations
- Zero weights effectively mark observations as missing — the penalty interpolates through gaps
None(default) treats all observations equally (equivalent toweights=1)
- Same length as
Constraint Parameters¶
-
constraints: Dictionary specifying boundary constraints"deriv": Derivative constraints at boundaries- Example:
{"deriv": {"order": 1, "initial": 0, "final": 0}}
-
slope_zero: Enforce flat slope in a subdomain- Example:
slope_zero=SlopeZeroConstraint(domain=(2.0, 4.0))
- Example:
Shape Constraint Parameters¶
-
shape: List ofShapeConstraintspecifications (§8.7)- Each entry is a
ShapeConstraintwithtype(required) and optionaldomain - Supported types:
"increasing","decreasing","convex","concave","nonneg" - Optional
domain=(lo, hi)restricts the constraint to that \(x\)-range - Multiple constraints can be combined (e.g. increasing + concave)
- Example:
[ShapeConstraint(type="increasing"), ShapeConstraint(type="concave", domain=(0, 5))]
- Each entry is a
-
shape_kappa: Large penalty weight for shape violations (default \(10^8\))- Higher values enforce the constraint more strictly
- Too large may cause numerical issues
-
max_shape_iter: Maximum iterations for the asymmetric-penalty loop (default 50)
Adaptive / Variable Penalty Parameters¶
-
adaptive: Enable nonparametric adaptive penalty (§8.8, defaultFalse)- Estimates spatially varying weights via a secondary B-spline basis
- Alternates between weight estimation and coefficient estimation
-
adaptive_nseg: Number of segments for the secondary weight basis (default 10) -
adaptive_lambda: Smoothing parameter for the weight basis (default 100.0) -
adaptive_max_iter: Maximum outer iterations for adaptive loop (default 20) -
penalty_gamma: Exponential variable penalty rate (§8.8, defaultNone)- When set, uses weights \(v_j = \exp(\gamma j / m)\)
- Positive \(\gamma\) → heavier penalty toward the right boundary
- Negative \(\gamma\) → heavier penalty toward the left boundary
None(default) uses the standard uniform penalty
Model Attributes¶
After fitting, the following attributes are available:
coef: B-spline coefficientsfitted_values: Fitted values at input pointsknots: Knot vector used for B-splinesED: Effective degrees of freedomphi_: Residual variance estimatese_coef: Standard errors of coefficientsse_fitted: Standard errors of fitted values
Error Handling¶
The PSpline class includes comprehensive input validation:
- Array validation: Checks for proper dimensions, finite values
- Parameter validation: Ensures valid ranges and types
- State validation: Verifies model is fitted before prediction
- Constraint validation: Validates constraint specifications
All errors provide descriptive messages with suggested solutions.