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.

Hashing Utilities

Deterministic hashing for reproducible data identification.

Hashing utilities for use case data models.

get_data_hash(data: UcData) -> str

Generate a deterministic hash from a UcData instance.

Serializes the data model to JSON using Pydantic's model_dump_json and returns a truncated SHA-256 hex digest.

Parameters:

  • data (UcData) –

    The use case data instance to hash.

Returns:

  • str

    A truncated SHA-256 hex string (first 8 characters).

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:

  • problem_type (str, default: None ) –

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

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:

  • expected (int | tuple[int, ...] | None, default: None ) –

    Expected size/length.

  • actual (int | tuple[int, ...] | None, default: None ) –

    Actual size/length.

  • field_name (str, default: 'arrays' ) –

    Name of the field with mismatched dimensions.

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:

  • field_name (str, default: 'Data' ) –

    Name of the field that is empty.

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:

  • field_name (str) –

    Name of the field with invalid value.

  • value (int | float, default: None ) –

    The invalid value.

  • constraint (str, default: 'valid' ) –

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

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:

  • element_id (int | str, default: None ) –

    Identifier of the problematic element.

  • reason (str, default: 'invalid structure' ) –

    Brief reason for the invalidity.

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:

  • data_type (str, default: 'data' ) –

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

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.