hgam 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.
Files changed (48) hide show
  1. hgam/__init__.py +10 -0
  2. hgam/api.py +116 -0
  3. hgam/engine/__init__.py +6 -0
  4. hgam/engine/gam_basis_cc.py +191 -0
  5. hgam/engine/gam_basis_cr.py +820 -0
  6. hgam/engine/gam_basis_fs.py +298 -0
  7. hgam/engine/gam_basis_parametric.py +133 -0
  8. hgam/engine/gam_basis_ps.py +176 -0
  9. hgam/engine/gam_basis_re.py +98 -0
  10. hgam/engine/gam_basis_t2.py +317 -0
  11. hgam/engine/gam_basis_te.py +224 -0
  12. hgam/engine/gam_basis_tp.py +362 -0
  13. hgam/engine/gam_derivatives.py +601 -0
  14. hgam/engine/gam_dispersion.py +111 -0
  15. hgam/engine/gam_family.py +579 -0
  16. hgam/engine/gam_fit.py +263 -0
  17. hgam/engine/gam_initial_sp.py +111 -0
  18. hgam/engine/gam_model.py +1193 -0
  19. hgam/engine/gam_predict.py +316 -0
  20. hgam/engine/gam_rank_pivot.py +149 -0
  21. hgam/engine/gam_reml.py +600 -0
  22. hgam/engine/gam_reml_appendix_b.py +364 -0
  23. hgam/engine/gam_reml_gradient.py +322 -0
  24. hgam/engine/gam_reml_hessian.py +427 -0
  25. hgam/engine/gam_reml_newton.py +639 -0
  26. hgam/engine/gam_reml_optimize.py +1006 -0
  27. hgam/engine/gam_select_penalty.py +121 -0
  28. hgam/engine/gam_term_build.py +820 -0
  29. hgam/engine/gam_term_spec.py +588 -0
  30. hgam/engine/gam_uncertainty.py +415 -0
  31. hgam/engine/gam_vcov.py +196 -0
  32. hgam/errors.py +40 -0
  33. hgam/frontend/__init__.py +30 -0
  34. hgam/frontend/api.py +1228 -0
  35. hgam/frontend/bam_fit.py +140 -0
  36. hgam/frontend/bam_fitd.py +586 -0
  37. hgam/frontend/davies.py +448 -0
  38. hgam/frontend/discrete.py +377 -0
  39. hgam/frontend/formula.py +542 -0
  40. hgam/frontend/gam_check.py +294 -0
  41. hgam/frontend/r_rng.py +117 -0
  42. hgam/frontend/smooth_tests.py +208 -0
  43. hgam/frontend/summary.py +386 -0
  44. hgam/frontend/threads.py +78 -0
  45. hgam-0.1.0.dist-info/METADATA +138 -0
  46. hgam-0.1.0.dist-info/RECORD +48 -0
  47. hgam-0.1.0.dist-info/WHEEL +4 -0
  48. hgam-0.1.0.dist-info/licenses/LICENSE +340 -0
hgam/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """hgam: hierarchical generalized additive models, ported from R's mgcv.
2
+
3
+ This package is a derivative work of mgcv (Simon N. Wood), licensed GPL (>= 2).
4
+ It is distributed under GPL-2.0-or-later. See LICENSE and docs/adr/0001-licence.md.
5
+ """
6
+
7
+ from hgam.api import bam, gam
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = ["bam", "gam", "__version__"]
hgam/api.py ADDED
@@ -0,0 +1,116 @@
1
+ """Public entry points. mgcv counterparts: ``gam`` (mgcv.r) and ``bam`` (bam.r), mgcv 1.9-4.
2
+
3
+ Both forward to :func:`hgam.frontend.api.gam`, which holds the verified subset: ``gam`` fits by exact
4
+ Laplace REML (``method="REML"``), ``bam`` by ``bgam.fitd``'s performance iteration on discretised
5
+ covariates (``method="fREML", discrete=TRUE``). Anything outside that subset is refused by name there.
6
+ """
7
+
8
+ from collections.abc import Mapping, Sequence
9
+
10
+ from hgam.errors import HgamNotImplementedError, HgamValidationError
11
+ from hgam.frontend.api import GamFit
12
+ from hgam.frontend.api import gam as _frontend_gam
13
+ from hgam.frontend.threads import blas_thread_limit, resolve_nthreads
14
+
15
+ __all__ = ["bam", "gam"]
16
+
17
+
18
+ def _family_with_link(family: str, link: str | None) -> str:
19
+ """``family`` as the front end reads it: ``binomial`` with ``link="cloglog"`` becomes
20
+ ``'binomial(link="cloglog")'``, as mgcv writes ``binomial(link = "cloglog")``."""
21
+ if link is None:
22
+ return family
23
+ if "(" in family:
24
+ raise HgamValidationError(
25
+ f"link={link!r} was given beside a family that already names its arguments ({family!r}); use one."
26
+ )
27
+ return f'{family}(link="{link}")'
28
+
29
+
30
+ def gam(
31
+ formula: str,
32
+ data: Mapping[str, object],
33
+ family: str = "gaussian",
34
+ *,
35
+ link: str | None = None,
36
+ weights: str | None = None,
37
+ offset: str | None = None,
38
+ select: bool = False,
39
+ knots: Mapping[str, Sequence[float]] | None = None,
40
+ method: str = "GCV.Cp",
41
+ control: Mapping[str, object] | None = None,
42
+ ) -> GamFit:
43
+ """Fit a GAM by REML. mgcv counterpart: ``gam`` (mgcv.r), mgcv 1.9-4.
44
+
45
+ Arguments are mgcv's where they exist (``family`` as a string such as ``'binomial(link="cloglog")'``,
46
+ or ``family="binomial", link="cloglog"``; ``weights`` and ``offset`` name columns of ``data``). Only
47
+ ``method="REML"`` is ported for ``gam``, so it must be written out: mgcv's default, ``method="GCV.Cp"``,
48
+ is refused by name rather than fitted by REML.
49
+
50
+ ``control`` is mgcv's ``control = gam.control(...)`` as a mapping; only
51
+ ``{"newton": {"conv.tol": value}}`` is ported (default ``1e-6``, as ``gam.control``), and every other
52
+ entry is refused by name.
53
+ """
54
+ if method != "REML":
55
+ raise HgamNotImplementedError(
56
+ f"hgam.gam(): method={method!r} is not ported; only method='REML' is, and it must be given "
57
+ "explicitly (mgcv's default is method='GCV.Cp'). Use hgam.bam for fREML."
58
+ )
59
+ return _frontend_gam(
60
+ formula,
61
+ data,
62
+ _family_with_link(family, link),
63
+ weights=weights,
64
+ offset=offset,
65
+ select=select,
66
+ knots=knots,
67
+ method="REML",
68
+ discrete=False,
69
+ control=control,
70
+ )
71
+
72
+
73
+ def bam(
74
+ formula: str,
75
+ data: Mapping[str, object],
76
+ family: str = "gaussian",
77
+ *,
78
+ link: str | None = None,
79
+ weights: str | None = None,
80
+ offset: str | None = None,
81
+ select: bool = False,
82
+ knots: Mapping[str, Sequence[float]] | None = None,
83
+ method: str = "fREML",
84
+ discrete: bool = False,
85
+ nthreads: int = 1,
86
+ ) -> GamFit:
87
+ """Fit a large GAM by fREML. mgcv counterpart: ``bam`` (bam.r), mgcv 1.9-4.
88
+
89
+ Arguments as :func:`gam`. Only ``method="fREML", discrete=True`` is ported (``bgam.fitd`` on
90
+ covariates binned as ``discrete.mf`` bins them); mgcv's default ``discrete=FALSE`` path
91
+ (``bgam.fit``) is refused by name.
92
+
93
+ ``nthreads`` (default 1, as in ``bam``) caps the BLAS thread pool for the length of the fit, through
94
+ the optional extra ``hgam[threads]`` (:mod:`hgam.frontend.threads`). It maps mgcv's argument name onto
95
+ BLAS: mgcv's ``nthreads`` drives mgcv's own OpenMP code, which hgam does not have. The cap is
96
+ process-wide while the fit runs and is restored afterwards. Without the extra, ``nthreads=1`` leaves
97
+ BLAS as the process set it and other values are refused; the two-element form is refused.
98
+ """
99
+ if (method, discrete) != ("fREML", True):
100
+ raise HgamNotImplementedError(
101
+ f"hgam.bam(): method={method!r}, discrete={discrete!r} is not ported; only method='fREML' with "
102
+ "discrete=True is (bgam.fitd). bam's discrete=FALSE path (bgam.fit) is not ported."
103
+ )
104
+ n_threads = resolve_nthreads(nthreads)
105
+ with blas_thread_limit(n_threads):
106
+ return _frontend_gam(
107
+ formula,
108
+ data,
109
+ _family_with_link(family, link),
110
+ weights=weights,
111
+ offset=offset,
112
+ select=select,
113
+ knots=knots,
114
+ method="fREML",
115
+ discrete=True,
116
+ )
@@ -0,0 +1,6 @@
1
+ """The GAM engine moved from polaris-re: bases, families, the penalised fit, REML and its
2
+ derivatives, smoothing-parameter search, covariance and prediction.
3
+
4
+ Moved as it was (M0); most of it was re-derived rather than ported line by line, and is replaced
5
+ by direct ports of mgcv where it differs from mgcv's path (see docs/PLAN.md, "After the move").
6
+ """
@@ -0,0 +1,191 @@
1
+ """The cyclic cubic regression spline, ``s(x, bs="cc")``: a cubic spline on ``k`` knots whose value, slope and
2
+ curvature match at the two end knots, so the first and last knot carry one coefficient (``k - 1`` columns).
3
+
4
+ mgcv counterpart: ``smooth.construct.cc.smooth.spec`` (with its local ``getBD``), ``place.knots``, ``cwrap``
5
+ and ``Predict.matrix.cyclic.smooth`` (smooth.r), mgcv 1.9-4, with knots placed or supplied. ``smoothCon`` then
6
+ applies ``scale.penalty`` and the ``colMeans(X)`` sum-to-zero constraint, exactly as for cr
7
+ (:func:`hgam.engine.gam_basis_cr.absorb_sum_to_zero_constraint`).
8
+
9
+ R's ``solve(B, D)`` (LAPACK ``dgesv``) is ``numpy.linalg.solve`` (the same LAPACK routine).
10
+ """
11
+
12
+ import numpy as np
13
+
14
+ from hgam.engine.gam_basis_cr import _r_norm_inf, _r_norm_one
15
+ from hgam.errors import HgamComputationError, HgamValidationError
16
+
17
+ __all__ = [
18
+ "CC_MIN_K",
19
+ "cc_basis",
20
+ "cc_bd",
21
+ "cc_knots",
22
+ "cc_predict_design",
23
+ "cc_wrap",
24
+ "place_knots",
25
+ ]
26
+
27
+ CC_MIN_K = 4
28
+ """``smooth.construct.cc.smooth.spec`` raises ``bs.dim`` below 4 to 4 with a warning; hgam refuses instead."""
29
+
30
+
31
+ def place_knots(x: np.ndarray, nk: int) -> np.ndarray:
32
+ """mgcv counterpart: ``place.knots`` (smooth.r), mgcv 1.9-4.
33
+
34
+ ``nk`` knots spread evenly through the sorted unique values of ``x``, the end knots at the extremes:
35
+ knot ``i`` (``i = 2, ..., nk - 1``) interpolates between the unique values at index
36
+ ``floor(delta * (i - 1)) + 1`` and the next one, with ``delta = (n - 1) / (nk - 1)``.
37
+ """
38
+ xu = np.unique(np.asarray(x, dtype=np.float64))
39
+ n = xu.size
40
+ if nk > n:
41
+ raise HgamValidationError("place_knots: more knots than unique data values is not allowed.")
42
+ if nk < 2:
43
+ raise HgamValidationError("place_knots: too few knots.")
44
+ if nk == 2:
45
+ return np.array([xu[0], xu[-1]], dtype=np.float64)
46
+ delta = (n - 1) / (nk - 1)
47
+ steps = delta * np.arange(1, nk - 1, dtype=np.float64)
48
+ lbi = np.floor(steps).astype(np.int64) + 1 # R's 1-based lower interval bound index
49
+ frac = steps + 1 - lbi
50
+ knots = np.zeros(nk, dtype=np.float64)
51
+ knots[0] = xu[0]
52
+ knots[-1] = xu[-1]
53
+ # x[lbi] and x.shift[lbi] = x[lbi + 1], 1-based.
54
+ knots[1:-1] = xu[lbi - 1] * (1 - frac) + xu[lbi] * frac
55
+ return knots
56
+
57
+
58
+ def cc_bd(knots: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
59
+ """mgcv counterpart: the local ``getBD`` of ``smooth.construct.cc.smooth.spec`` and ``BD <- solve(B, D)``
60
+ (smooth.r), mgcv 1.9-4.
61
+
62
+ Returns ``(B, D, BD)``, each ``(k - 1, k - 1)``: ``B m = D p`` ties the second derivatives ``m`` at the
63
+ knots (all but the last) to the values ``p`` (Lancaster and Salkauskas, section 4.7, wrapped for
64
+ periodicity).
65
+ """
66
+ knots = np.asarray(knots, dtype=np.float64)
67
+ h = np.diff(knots)
68
+ n = knots.size - 1
69
+ if n < 3:
70
+ raise HgamValidationError(f"cc_bd: {knots.size} knots; a cyclic cubic spline needs at least 4.")
71
+ if np.any(h <= 0.0):
72
+ raise HgamValidationError("cc_bd: the knots must be strictly increasing.")
73
+ b = np.zeros((n, n), dtype=np.float64)
74
+ d = np.zeros((n, n), dtype=np.float64)
75
+ b[0, 0] = (h[n - 1] + h[0]) / 3
76
+ b[0, 1] = h[0] / 6
77
+ b[0, n - 1] = h[n - 1] / 6
78
+ d[0, 0] = -(1 / h[0] + 1 / h[n - 1])
79
+ d[0, 1] = 1 / h[0]
80
+ d[0, n - 1] = 1 / h[n - 1]
81
+ for i in range(1, n - 1):
82
+ b[i, i - 1] = h[i - 1] / 6
83
+ b[i, i] = (h[i - 1] + h[i]) / 3
84
+ b[i, i + 1] = h[i] / 6
85
+ d[i, i - 1] = 1 / h[i - 1]
86
+ d[i, i] = -(1 / h[i - 1] + 1 / h[i])
87
+ d[i, i + 1] = 1 / h[i]
88
+ b[n - 1, n - 2] = h[n - 2] / 6
89
+ b[n - 1, n - 1] = (h[n - 2] + h[n - 1]) / 3
90
+ b[n - 1, 0] = h[n - 1] / 6
91
+ d[n - 1, n - 2] = 1 / h[n - 2]
92
+ d[n - 1, n - 1] = -(1 / h[n - 2] + 1 / h[n - 1])
93
+ d[n - 1, 0] = 1 / h[n - 1]
94
+ return b, d, np.linalg.solve(b, d)
95
+
96
+
97
+ def cc_wrap(x0: float, x1: float, x: np.ndarray) -> np.ndarray:
98
+ """mgcv counterpart: ``cwrap`` (smooth.r), mgcv 1.9-4: map ``x`` onto ``[x0, x1]`` periodically. R's
99
+ ``%%`` is the floored modulus, as ``numpy.mod`` is for a positive period."""
100
+ x = np.array(x, dtype=np.float64, copy=True)
101
+ h = x1 - x0
102
+ above = x > x1
103
+ if above.any():
104
+ x[above] = x0 + np.mod(x[above] - x1, h)
105
+ below = x < x0
106
+ if below.any():
107
+ x[below] = x1 - np.mod(x0 - x[below], h)
108
+ return x
109
+
110
+
111
+ def cc_predict_design(x: np.ndarray, knots: np.ndarray, bd: np.ndarray) -> np.ndarray:
112
+ """mgcv counterpart: ``Predict.matrix.cyclic.smooth`` and its local ``pred.mat`` (smooth.r), mgcv 1.9-4.
113
+
114
+ Each ``x`` (wrapped by :func:`cc_wrap` when any lies outside the knots) falls in the interval ending at
115
+ the first knot not below it; the row is the cubic spline's value in terms of the knot values, with the
116
+ last knot identified with the first.
117
+ """
118
+ x = np.asarray(x, dtype=np.float64)
119
+ knots = np.asarray(knots, dtype=np.float64)
120
+ if x.size < 1:
121
+ raise HgamValidationError("cc_predict_design: no data to predict at.")
122
+ n = knots.size
123
+ h = np.diff(knots)
124
+ if np.max(x) > knots[-1] or np.min(x) < knots[0]:
125
+ x = cc_wrap(float(knots[0]), float(knots[-1]), x)
126
+ # for (i in n:2) j[x <= knots[i]] <- i: the smallest 1-based i >= 2 with x <= knots[i].
127
+ j = np.maximum(np.searchsorted(knots, x, side="left"), 1) # 0-based right knot index
128
+ j1 = j - 1 # 0-based left knot index, also hj
129
+ j = np.where(j == n - 1, 0, j)
130
+ eye = np.eye(n - 1, dtype=np.float64)
131
+ hj = h[j1]
132
+ right = knots[j1 + 1] - x
133
+ left = x - knots[j1]
134
+ out = (
135
+ bd[j1] * (right**3 / (6 * hj))[:, None]
136
+ + bd[j] * (left**3 / (6 * hj))[:, None]
137
+ - bd[j1] * (hj * right / 6)[:, None]
138
+ - bd[j] * (hj * left / 6)[:, None]
139
+ + eye[j1] * (right / hj)[:, None]
140
+ + eye[j] * (left / hj)[:, None]
141
+ )
142
+ return np.asarray(out, dtype=np.float64)
143
+
144
+
145
+ def cc_knots(x: np.ndarray, k: int, supplied: np.ndarray | None = None) -> np.ndarray:
146
+ """mgcv counterpart: the knot branch of ``smooth.construct.cc.smooth.spec`` (smooth.r), mgcv 1.9-4.
147
+
148
+ ``k <- knots[[object$term]]``: with none supplied, ``place.knots(x, nk)``; with two values (a range),
149
+ ``place.knots(c(k, x), nk)``, so the range's ends join ``x``'s unique values; otherwise the supplied
150
+ vector is used as it is, and a length other than ``nk`` stops (``"number of supplied knots != k for a cc
151
+ smooth"``).
152
+ """
153
+ x = np.asarray(x, dtype=np.float64)
154
+ if supplied is None:
155
+ return place_knots(x, k)
156
+ supplied = np.asarray(supplied, dtype=np.float64)
157
+ if supplied.size == 2:
158
+ return place_knots(np.concatenate([supplied, x]), k)
159
+ if supplied.size != k:
160
+ raise HgamValidationError(
161
+ f"cc_knots: {supplied.size} supplied knots != k ({k}) for a cc smooth (mgcv stops here too)."
162
+ )
163
+ return supplied.copy()
164
+
165
+
166
+ def cc_basis(
167
+ x: np.ndarray, k: int, knots: np.ndarray | None = None
168
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
169
+ """The **unconstrained** cc design ``(n, k - 1)`` and ``smoothCon``-scaled penalty, the knots and ``BD``.
170
+
171
+ mgcv counterpart: ``smooth.construct.cc.smooth.spec`` (smooth.r), mgcv 1.9-4: the knots by
172
+ :func:`cc_knots` (``knots`` is the supplied ``knots[[term]]``, or ``None``), the penalty ``t(D) %*% BD``
173
+ made exactly symmetric, the design ``Predict.matrix.cyclic.smooth`` (``x`` outside the knots wrapped by
174
+ ``cwrap``); then ``smoothCon``'s ``scale.penalty``, ``S / (norm(S) / norm(X, "I")^2)``, as
175
+ :func:`~hgam.engine.gam_basis_cr.cr_basis`.
176
+ """
177
+ x = np.asarray(x, dtype=np.float64)
178
+ if k < CC_MIN_K:
179
+ raise HgamValidationError(
180
+ f"cc_basis: k={k}; a cyclic cubic spline needs k >= {CC_MIN_K} "
181
+ "(mgcv raises it to 4 with a warning)."
182
+ )
183
+ knots = cc_knots(x, k, knots)
184
+ _, d, bd = cc_bd(knots)
185
+ s = d.T @ bd
186
+ s = (s + s.T) / 2
187
+ design = cc_predict_design(x, knots, bd)
188
+ norm_x = _r_norm_inf(design) ** 2
189
+ if norm_x == 0.0:
190
+ raise HgamComputationError("cc_basis: the design matrix is identically zero.")
191
+ return design, s / (_r_norm_one(s) / norm_x), knots, bd