Make use of NumPy's array input validation in ``validate_arguments`` and ``shape_from_args``
In #2597 , we first implemented this idea of using mock numpy arrays to take advantage of their input validation API. See the example here. This allows us to reduce lines of code and get the exact some error messages as NumPy if there are invalid inputs, thereby reducing some developer burden. This could be done for many more atoms that have numpy analogs such as vstack, hstack and sum (AxisAtom).
Another side-related issue is that these errors will come from NumPy and could confuse cvxpy users. The ideal situation would be to get the NumPy error message and adapt it to our use-case (maybe just mention that this error was raised from cp.Concatenate for example).
I love this idea!
On Sun, Nov 3, 2024 at 5:14 PM William Zijie Zhang @.***> wrote:
In #2597 https://github.com/cvxpy/cvxpy/pull/2597 , we first implemented this idea of using mock numpy arrays to take advantage of their input validation API. See the example here https://github.com/cvxpy/cvxpy/pull/2597/files#r1825978426. This allows us to reduce lines of code and get the exact some error messages as NumPy if there are invalid inputs, thereby reducing some developer burden. This could be done for many more atoms that have numpy analogs such as vstack, hstack and sum (AxisAtom).
Another side-related issue is that these errors will come from NumPy and could confuse cvxpy users. The ideal situation would be to get the NumPy error message and adapt it to our use-case (maybe just mention that this error was raised from cp.Concatenate for example).
— Reply to this email directly, view it on GitHub https://github.com/cvxpy/cvxpy/issues/2613, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACRLIFFJZK6NFUA6RQW5N4DZ62G5DAVCNFSM6AAAAABRDEFVZGVHI2DSMVQWIX3LMV43ASLTON2WKOZSGYZTCNJRGMZTAMY . You are receiving this because you are subscribed to this thread.Message ID: @.***>
Could be something like this
# cvxpy/errors.py
class ShapeValidationError(Exception):
"""
Custom exception for shape validation errors in CVXPY.
This exception forwards NumPy shape errors while preserving
the original error message and traceback.
"""
@classmethod
def from_numpy_error(cls, numpy_error):
raise cls(f"Forwarded numpy validation error: {str(numpy_error)}") from numpy_error
and then
import numpy as np
from cvxpy.errors import ShapeValidationError
class Hstack(AffAtom):
""" Horizontal concatenation """
def validate_arguments(self) -> None
try:
np.hstack([np.empty(arg.shape, dtype = np.dtype([])) for arg in self.args])
except ValueError as exc:
ShapeValidationError.from_numpy_error(exc)
#2976 resolves this issue, thanks @7astro7 , really nice work!