Skip to content

Utils API Reference

This module provides shared utilities used across all use cases.

NumPy Array Validator

Custom Pydantic type for handling NumPy arrays in data models.

nd_array_before_validator(x: np.ndarray | list[Any] | str) -> np.ndarray

Convert input to numpy array.

nd_array_symmetric_validator(x: np.ndarray) -> np.ndarray

Check if a numpy array is a symmetric matrix.

Raises ValueError if input is not 2D or not square. Converts upper or lower triangular matrices to symmetric numpy array.

nd_array_binary_adj_validator(x: np.ndarray) -> np.ndarray

Ensure matrix is a binary adjacency matrix (values 0 or 1).

nd_array_weighted_adj_validator(x: np.ndarray) -> np.ndarray

Ensure matrix is a valid weighted adjacency matrix.

nd_array_serializer(x: np.ndarray) -> list[Any]

Serialize numpy array to list.

Error Types

Domain-specific exceptions for validation and solution interpretation.

Custom error classes for use case formulations and solutions.

This module provides a hierarchy of custom exceptions to replace generic ValueError exceptions, giving users more specific and helpful error messages.

UseCaseError

Bases: Exception

Base exception class for all use case errors.

NoSolutionFoundError

Bases: UseCaseError

Raised when the solver fails to find a solution.

This typically occurs when the optimization problem has no feasible solution or the solver was unable to find one within the given constraints.

Parameters:

Name Type Description Default
problem_type str

The type of problem being solved (e.g., "Set Cover", "Knapsack"). If provided, will be included in the error message.

None

Examples:

No solution found
if best is None:
    raise NoSolutionFoundError()

# Or with problem type:
raise NoSolutionFoundError(problem_type="Set Cover")

InvalidInputDataError

Bases: UseCaseError

Base exception for input data validation errors.

Use specific subclasses when possible to provide more context.

DataShapeMismatchError

Bases: InvalidInputDataError

Raised when array dimensions or shapes don't match expected values.

Parameters:

Name Type Description Default
expected int | tuple[int, ...] | None

Expected size/length.

None
actual int | tuple[int, ...] | None

Actual size/length.

None
field_name str

Name of the field with mismatched dimensions.

'arrays'

Examples:

Shape mismatch between arrays
if w.shape[0] != c.shape[0]:
    raise DataShapeMismatchError(
        expected=w.shape[0],
        actual=c.shape[0],
        field_name="weights and values",
    )

EmptyDataError

Bases: InvalidInputDataError

Raised when required data is empty or has zero size.

Parameters:

Name Type Description Default
field_name str

Name of the field that is empty.

'Data'

Examples:

Empty subset matrix
if subset_matrix.size == 0:
    raise EmptyDataError(field_name="Subset matrix")

InvalidValueError

Bases: InvalidInputDataError

Raised when a value is out of the valid range.

Parameters:

Name Type Description Default
field_name str

Name of the field with invalid value.

required
value int | float

The invalid value.

None
constraint str

Description of the constraint (e.g., "non-negative", "positive").

'valid'

Examples:

Negative capacity value
if capacity < 0:
    raise InvalidValueError(
        field_name="Capacity",
        value=capacity,
        constraint="non-negative",
    )

InvalidProblemStructureError

Bases: InvalidInputDataError

Raised when the problem structure is invalid or infeasible.

This includes cases where constraints cannot be satisfied due to problem definition issues.

Parameters:

Name Type Description Default
element_id int | str

Identifier of the problematic element.

None
reason str

Brief reason for the invalidity.

'invalid structure'

Examples:

Uncovered element in problem
if not subsets_containing_element:
    raise InvalidProblemStructureError(
        element_id=element_idx,
        reason="not covered by any subset",
    )

DataCollectionError

Bases: UseCaseError

Base exception for data collection errors.

NoValidDataError

Bases: DataCollectionError

Raised when no valid data is found in a collection.

Parameters:

Name Type Description Default
data_type str

Type of data that was expected (e.g., "ticker", "instance").

'data'

Examples:

No valid ticker data found
if not valid_returns:
    raise NoValidDataError(data_type="ticker")

InvalidValueRangeError

Bases: InvalidInputDataError

Raised when a value is out of the valid range.