Coverage for src/cvxcla/_lasso_validate.py: 100%
68 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 13:36 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 13:36 +0000
1"""Input validation for :class:`cvxcla.lasso.Lasso` construction.
3The LASSO accepts its quadratic form either as a dense design ``(x, y)`` or as a
4``QuadraticForm`` operator plus the linear term ``X^T y``, optionally with linear
5inequality constraints ``G beta <= h``. The shape and consistency checks for those
6two input modes, plus the constraint checks, are pure functions here so
7``Lasso.__post_init__`` reduces to dispatching to them before handing off to the
8tracer.
9"""
11from __future__ import annotations
13import numpy as np
14from numpy.typing import NDArray
16from .operators import QuadraticForm
19def validate_operator_inputs(
20 quad_form: QuadraticForm | None,
21 linear: NDArray[np.float64] | None,
22 x: NDArray[np.float64] | None,
23 y: NDArray[np.float64] | None,
24) -> NDArray[np.float64]:
25 """Validate the operator-mode inputs ``quad_form`` and ``linear`` (``X^T y``).
27 Args:
28 quad_form: The quadratic form ``H`` as a :class:`QuadraticForm` operator.
29 linear: The linear term ``X^T y`` (must be the 1d vector).
30 x: The dense design matrix, which must be absent in operator mode.
31 y: The dense response vector, which must be absent in operator mode.
33 Returns:
34 The validated ``linear`` term as a 1d ``float64`` array.
36 Raises:
37 ValueError: If only one of ``quad_form``/``linear`` is given, a design
38 ``(x, y)`` is also supplied, or ``linear`` is not the 1d ``X^T y``.
39 """
40 if quad_form is None or linear is None:
41 msg = "quad_form and linear (X^T y) must be provided together"
42 raise ValueError(msg)
43 _reject_conflicting_design(x, y)
44 linear = np.asarray(linear, dtype=np.float64)
45 if linear.ndim != 1:
46 msg = f"linear must be the 1d vector X^T y, got shape {linear.shape}"
47 raise ValueError(msg)
48 return linear
51def _reject_conflicting_design(x: NDArray[np.float64] | None, y: NDArray[np.float64] | None) -> None:
52 """Reject a dense design ``(x, y)`` supplied alongside the operator inputs.
54 Args:
55 x: The dense design matrix, which must be absent in operator mode.
56 y: The dense response vector, which must be absent in operator mode.
58 Raises:
59 ValueError: If either ``x`` or ``y`` is provided.
60 """
61 if x is not None or y is not None:
62 msg = "supply either a design (x, y) or an operator (quad_form, linear), not both"
63 raise ValueError(msg)
66def validate_design_inputs(x: NDArray[np.float64] | None, y: NDArray[np.float64] | None) -> None:
67 """Validate the dense-design inputs ``x`` and ``y``.
69 Args:
70 x: The design matrix of shape ``(m, n)``.
71 y: The response vector of shape ``(m,)``.
73 Raises:
74 ValueError: If ``x``/``y`` are missing, ``x`` is not a 2d design matrix,
75 or ``y``'s length does not match ``x``'s row count.
76 """
77 if x is None or y is None:
78 msg = "provide a design (x, y) or an operator (quad_form, linear)"
79 raise ValueError(msg)
80 if x.ndim != 2:
81 msg = f"x must be a 2d design matrix, got shape {x.shape}"
82 raise ValueError(msg)
83 if y.shape != (x.shape[0],):
84 msg = f"y must have shape ({x.shape[0]},), got {y.shape}"
85 raise ValueError(msg)
88def validate_constraints(
89 g: NDArray[np.float64] | None,
90 h: NDArray[np.float64] | None,
91 dimension: int,
92 tol: float,
93) -> None:
94 """Validate the optional inequality constraints ``G beta <= h``.
96 Args:
97 g: Inequality matrix ``G`` of ``G beta <= h`` (``None`` for the plain LASSO).
98 h: Inequality right-hand side ``h`` (``None`` for the plain LASSO).
99 dimension: The problem dimension ``n`` (number of features).
100 tol: Tolerance below which an ``h`` entry counts as non-positive.
102 A negative ``h`` entry, a row that excludes ``beta = 0``, is allowed: the penalty
103 form starts such a path from the smallest-``l1`` point on the constraints rather than
104 from ``beta = 0`` (see :mod:`cvxcla._lasso_bounded`).
106 Raises:
107 ValueError: If only one of ``g``/``h`` is given, their shapes are
108 inconsistent with the problem dimension, or an ``h`` entry is in
109 ``(0, tol]``.
110 """
111 if g is None and h is None:
112 return
113 if g is None or h is None:
114 msg = "g and h must be provided together"
115 raise ValueError(msg)
116 _validate_constraint_shapes(g, h, dimension, tol)
119def _validate_constraint_shapes(
120 g: NDArray[np.float64],
121 h: NDArray[np.float64],
122 dimension: int,
123 tol: float,
124) -> None:
125 """Validate the shapes of a fully-provided ``G beta <= h``, and that no ``h`` entry is nearly zero.
127 Args:
128 g: Inequality matrix ``G`` (both ``g`` and ``h`` known to be present).
129 h: Inequality right-hand side ``h``.
130 dimension: The problem dimension ``n`` (number of features).
131 tol: Tolerance below which an ``h`` entry counts as non-positive.
133 Raises:
134 ValueError: If ``g``'s shape is inconsistent with ``h`` and the problem
135 dimension, or an ``h`` entry lies in ``(0, tol]``, too close to zero to
136 start from and not zero.
137 """
138 if g.shape != (h.shape[0], dimension):
139 msg = f"g must have shape ({h.shape[0]}, {dimension}), got {g.shape}"
140 raise ValueError(msg)
141 if np.any((h > 0) & (h <= tol)):
142 msg = f"h entries in (0, {tol:g}] are too close to zero to start from; pass 0 for a homogeneous row"
143 raise ValueError(msg)
146def validate_equality(a: NDArray[np.float64], dimension: int) -> NDArray[np.float64]:
147 """Validate the equality constraints ``A beta = b``.
149 Args:
150 a: Equality matrix ``A`` of ``A beta = b``.
151 dimension: The problem dimension ``n`` (number of features).
153 Returns:
154 ``a`` as a 2d ``float64`` array.
156 Raises:
157 ValueError: If ``a`` is not a 2d matrix with ``n`` columns.
158 """
159 a = np.asarray(a, dtype=np.float64)
160 if a.ndim != 2 or a.shape[1] != dimension:
161 msg = f"a must have shape (m, {dimension}), got {a.shape}"
162 raise ValueError(msg)
163 return a
166def validate_bounds(
167 lower: NDArray[np.float64] | None,
168 upper: NDArray[np.float64] | None,
169 b: NDArray[np.float64] | None,
170 a: NDArray[np.float64] | None,
171 nonneg: bool,
172 dimension: int,
173) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
174 """Validate per-coefficient bounds ``lower <= beta <= upper`` and the right-hand side ``b``.
176 Args:
177 lower: Lower bounds, each ``<= 0`` (``-inf`` allowed); ``None`` for none.
178 upper: Upper bounds, each ``>= 0`` (``inf`` allowed); ``None`` for none.
179 b: Right-hand side of ``A beta = b``; ``None`` for ``b = 0``.
180 a: The (validated) equality matrix, or ``None``.
181 nonneg: Whether ``beta >= 0`` was requested, which tightens ``lower`` to ``0``.
182 dimension: The problem dimension ``n`` (number of features).
184 Returns:
185 ``(lower, upper, b)`` as ``float64`` arrays, with absent bounds infinite and
186 an absent ``b`` zero.
188 Raises:
189 ValueError: If a bound has the wrong shape or excludes ``beta_j = 0``, or
190 ``b`` is given without ``a`` or with the wrong length.
191 """
192 lo = np.full(dimension, -np.inf) if lower is None else np.asarray(lower, dtype=np.float64)
193 up = np.full(dimension, np.inf) if upper is None else np.asarray(upper, dtype=np.float64)
194 if lo.shape != (dimension,) or up.shape != (dimension,):
195 msg = f"lower and upper must have shape ({dimension},), got {lo.shape} and {up.shape}"
196 raise ValueError(msg)
197 if np.any(lo > 0) or np.any(up < 0):
198 msg = (
199 "bounds must admit beta_j = 0: every lower bound <= 0 and every upper bound >= 0; "
200 "pass a bound that excludes zero as a row of g beta <= h, e.g. -beta_j <= -l_j"
201 )
202 raise ValueError(msg)
203 if nonneg:
204 lo = np.maximum(lo, 0.0)
205 rows = 0 if a is None else a.shape[0]
206 if b is not None and a is None:
207 msg = "a right-hand side b needs equality rows a"
208 raise ValueError(msg)
209 rhs = np.zeros(rows) if b is None else np.asarray(b, dtype=np.float64).reshape(-1)
210 if rhs.shape != (rows,):
211 msg = f"b must have shape ({rows},), got {rhs.shape}"
212 raise ValueError(msg)
213 return lo, up, rhs