Skip to content

Replace assert with proper validation in channel_to_kraus()#134

Merged
gecrooks merged 1 commit intogecrooks:mainfrom
ddri:fix/issue-131-channel-validation
Dec 19, 2025
Merged

Replace assert with proper validation in channel_to_kraus()#134
gecrooks merged 1 commit intogecrooks:mainfrom
ddri:fix/issue-131-channel-validation

Conversation

@ddri
Copy link
Contributor

@ddri ddri commented Dec 19, 2025

Summary

  • Replace assert statements with proper if/raise ValueError
  • Add descriptive error messages with diagnostic values
  • Handle numerical noise gracefully
  • Add complete docstring

Problem

The function used assertions for critical validation:

assert np.allclose(evals.imag, 0.0)  # FIXME exception
assert np.all(evals.real >= 0.0)  # FIXME exception

Running python -O disables assertions, causing invalid channels to silently produce garbage Kraus operators with NaN values (from sqrt of negative numbers).

Demonstrated with -O flag before fix:

RuntimeWarning: invalid value encountered in sqrt
  values = np.sqrt(evals.real)

Fix

if not np.allclose(evals.imag, 0.0):
    max_imag = np.max(np.abs(evals.imag))
    raise ValueError(
        f"Choi matrix has non-real eigenvalues (max imaginary: {max_imag:.2e}). "
        "Channel may not be Hermitian-preserving."
    )

if np.any(evals.real < -1e-9):
    min_eval = np.min(evals.real)
    raise ValueError(
        f"Choi matrix has negative eigenvalues (min: {min_eval:.2e}). "
        "Channel may not be completely positive."
    )

# Clamp small negative values from numerical noise to zero
values = np.sqrt(np.maximum(evals.real, 0.0))

Test plan

  • Valid channels still convert correctly
  • Invalid channels raise ValueError (not AssertionError)
  • Validation works even with python -O flag
  • All existing channels_test.py tests pass (32 tests)

Fixes #131

The function used assert statements to validate Choi matrix eigenvalues.
This is problematic because assertions are disabled with `python -O`,
allowing invalid channels to produce garbage Kraus operators (with NaN
values from sqrt of negative numbers).

Changes:
- Replace asserts with if/raise ValueError
- Add descriptive error messages with diagnostic info (actual values)
- Add small tolerance (-1e-9) for numerical noise on negative check
- Clamp tiny negative values to zero before sqrt to handle numerical noise
- Add full docstring with Args, Returns, and Raises sections
- Remove # TESTME comment (function is tested via test_askraus)

Fixes gecrooks#131
@gecrooks gecrooks merged commit c69bf6d into gecrooks:main Dec 19, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: assert used for numerical validation in channel_to_kraus()

2 participants