Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions pretab/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ class RepresentationConformanceError(PretabError, AssertionError):


# --- Message factories ---
def _sorted_for_display(values):
"""Return ``values`` sorted for an error message, even when they mix types.

Column labels can mix ints and strings (e.g. ``pd.concat`` of a named frame and
an unnamed array), which ``sorted`` cannot compare; those are ordered by their
string form so the actual error is still raised.
"""
values = list(values)
try:
return sorted(values)
except TypeError:
return sorted(values, key=lambda value: (str(value), type(value).__name__))


def invalid_param_error(estimator, param, value, constraint, valid=None):
"""Build an :class:`InvalidParamError` with a consistent, actionable message.

Expand All @@ -129,11 +143,13 @@ def invalid_param_error(estimator, param, value, constraint, valid=None):
constraint : str
Human-readable description of the constraint that was violated.
valid : iterable, optional
The set of valid values, listed in the message when provided.
The set of valid values, listed in the message when provided. Values that
cannot be compared with each other (such as mixed int and str column
labels) are listed in the order of their string form.
"""
msg = f"{estimator}.{param} = {value!r} is invalid.\nConstraint: {constraint}"
if valid is not None:
msg += f"\nValid values: {sorted(valid)}"
msg += f"\nValid values: {_sorted_for_display(valid)}"
return InvalidParamError(msg)


Expand Down
3 changes: 2 additions & 1 deletion pretab/preprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
PretabConfigError,
PretabDataError,
PretabSerializationError,
_sorted_for_display,
invalid_param_error,
)
from .expansion.spline.multivariate.tensor_product import TensorProductSplineTransformer
Expand Down Expand Up @@ -867,7 +868,7 @@ def _validate_feature_overrides(self, frame):
raise invalid_param_error(
type(self).__name__,
"feature_preprocessing",
sorted(unknown_features),
_sorted_for_display(unknown_features),
"every key must name a column present in X",
valid=frame.columns,
)
Expand Down
26 changes: 26 additions & 0 deletions tests/integration/test_column_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,3 +699,29 @@ def test_underscore_and_integer_labels_preserve_routing_and_public_metadata():
np.testing.assert_array_equal(out[f"num_{label}"].ravel(), frame[label].to_numpy())
np.testing.assert_array_equal(out["cat_0"].ravel(), [2.0, 1.0, 2.0, 1.0, 2.0, 2.0])
pd.testing.assert_frame_equal(frame, original)


def _mixed_label_frame():
rng = np.random.default_rng(0)
named = pd.DataFrame({"age": rng.uniform(20, 70, 60)})
return pd.concat([named, pd.DataFrame(rng.normal(size=(60, 2)))], axis=1), rng.normal(size=60)


@pytest.mark.parametrize(
"options",
[
{"feature_preprocessing": {"agee": "rbf"}},
{"feature_preprocessing": {"agee": "rbf", 5: "rbf"}},
{"feature_groups": [{"name": "pair", "columns": ["age", 3], "representation": "tensorspline"}]},
],
ids=["override", "two-overrides", "group-source"],
)
def test_unknown_column_with_mixed_labels_raises_invalid_param_error(options):
"""With mixed int/str labels, sorting the valid labels for the message raised a
TypeError instead of the actionable InvalidParamError."""
from pretab.exceptions import InvalidParamError

X, y = _mixed_label_frame()
assert list(X.columns) == ["age", 0, 1]
with pytest.raises(InvalidParamError, match=r"Valid values: \[0, 1, 'age'\]"):
Preprocessor(**options).fit(X, y)
13 changes: 13 additions & 0 deletions tests/integration/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@ def test_warning_hierarchy():
# --------------------------------------------------------------------------- #


def test_invalid_param_error_lists_mixed_type_valid_values():
"""Mixed int/str column labels cannot be compared, and sorting them raised a
TypeError that replaced the actual error."""
err = invalid_param_error("Foo", "columns", "agee", "must name a column", valid=pd.Index(["age", 0, 1]))
assert isinstance(err, InvalidParamError)
assert "Valid values: [0, 1, 'age']" in str(err)


def test_invalid_param_error_keeps_the_natural_order_of_comparable_values():
err = invalid_param_error("Foo", "columns", 3, "must name a column", valid=[10, 2, 1])
assert "Valid values: [1, 2, 10]" in str(err)


def test_invalid_param_error_message_has_value_constraint_and_valid():
err = invalid_param_error(
"Foo",
Expand Down
Loading